Thursday, February 27, 2014

Type Casting

Type Casting

Def:  The  process  of  converting  the  value  from  one  data  type  to  another  data  type  is
         called as Casting. This is of two types.
  • Implicit Casting:
            The  value  can  be  converted  by  the  compiler  automatically,  without  using  any extra statement.
  • Explicit Casting:
            The value can be converted by the programmer using a conversion method.

Implicit Casting

Implicit casting is possible in the following cases.
  • Any numerical value from lower to higher type.
              Ex: byte to short
                   short to int
                   float to double
  • Any numerical value from non-decimal type to decimal type.
              Ex: int to float
                    long to double
      The following table shows the all possible implicit conversions supported by C#

Implicit Casting in C#:

Explicit Casting

Explicit casting should be performed in the following cases:
  • Any numerical value from higher type to lower type.
  • Any numerical value from decimal type to non-decimal type.
  • Any value from numerical type to non-numerical type.
  • Any value from non-numerical type to numerical type.
  • Syn:  (target data type)variable
  •          (target data type)value

Download above Code of Demo of Casting : Download Links

Explicit Casting using Conversion Methods

Explicit casting can also be performed by using the ―Conversion methods‖. The ―System.Convert‖
class provides several methods to perform explicit casting.

  • System.Convert.ToSByte(value);
           Converts the value into "sbyte" type.

  • System.Convert.ToByte(value);
           Converts the value into "byte" type.

  • System.Convert.ToInt16(value);
           Converts the value into "short" type.

  • System.Convert.ToUInt16(value);
           Converts the value into "ushort" type.

  • System.Convert.ToInt32(value);
           Converts the value into "int" type.

  • System.Convert.ToUInt32(value);
          Converts the value into "uint" type.

  • System.Convert.ToInt64(value);
          Converts the value into "long" type.

  • System.Convert.ToUInt64(value);
          Converts the value into "ulong" type.

  • System.Convert.ToSingle(value);
          Converts the value into "float" type.

  • System.Convert.ToDouble(value);
          Converts the value into "double" type.

  • System.Convert.ToDecimal(value);
          Converts the value into "decimal" type.

  • System.Convert.ToChar(value);
           Converts the value into "char" type.

  • System.Convert.ToString(value);
            Converts the value into "string" type.

  • System.Convert.ToBoolean(value);
            Converts the value into "bool" type

Download above Code of Demo on Casting and Conversion Methods : Download Links

No comments:

Post a Comment