none
type conversion :Coercion

Answers

  • Hi,

    Implicit and explicit are two kind of typecasts.

    Consider the scenario of predefined types and implicit,explicit casts.

    Int i = 3;
    long l = i ; //implicit, no data lose as long has 8 bytes and int has 4 bytes
    short s = (shor) i; //explicit, data byte can occur as short is only two byte and int is 4 byte.


    In case of Custom types you need to write your own implict and explicit casts (syntax looks like operator overloading).

    Assume you have a class Currency and you need to  assing float value to Currency object and vice versa. So you need to write implicit and explicit cast inside Currency class as follows.

    class Currency
    {
      int m_Dollars, m_Cents;
      public Currency(float dollars,float cents)
      {
            m_Dollars = dollars; m_Cents = cents;
      }

      public static implicit operator float(Currency value)
      {
          return value.m_Dollars + (value.m_Cents / 100);
      }
     
      public static explicit operator Currency(float value)
      {
          int doll = (int)value;
          int cents = (value - doll) * 100)
          return new Currency(doll,  cents);
      }
    }

    Hope this clarifies

    Best regards
    MadeInCode
    www.MadeInCode.com




    Thursday, August 23, 2007 3:55 PM