C# - Type Conversion

Advertisements


Type conversion is basically type casting or converting one type of data to another type. In C#, type casting has two forms:

  • Implicit type conversion - these conversions are performed by C# in a type-safe manner. Examples are conversions from smaller to larger integral types and conversions from derived classes to base classes.

  • Explicit type conversion - these conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion:

namespace TypeConversionApplication
{
    class ExplicitConversion
    {
        static void Main(string[] args)
        {
            double d = 5673.74;
            int i;

            // cast double to int.
            i = (int)d;
            Console.WriteLine(i);
            Console.ReadKey();
            
        }
    }
}

When the above code is compiled and executed, it produces the following result:

5673

C# Type Conversion Methods

C# provides the following built-in type conversion methods:

S.NMethods & Description
1ToBoolean
Converts a type to a Boolean value, where possible.
2ToByte
Converts a type to a byte.
3ToChar
Converts a type to a single Unicode character, where possible.
4ToDateTime
Converts a type (integer or string type) to date-time structures.
5ToDecimal
Converts a floating point or integer type to a decimal type.
6ToDouble
Converts a type to a double type.
7ToInt16
Converts a type to a 16-bit integer.
8ToInt32
Converts a type to a 32-bit integer.
9ToInt64
Converts a type to a 64-bit integer.
10ToSbyte
Converts a type to a signed byte type.
11ToSingle
Converts a type to a small floating point number.
12ToString
Converts a type to a string.
13ToType
Converts a type to a specified type.
14ToUInt16
Converts a type to an unsigned int type.
15ToUInt32
Converts a type to an unsigned long type.
16ToUInt64
Converts a type to an unsigned big integer.

The following example converts various value types to string type:

namespace TypeConversionApplication
{
    class StringConversion
    {
        static void Main(string[] args)
        {
            int i = 75;
            float f = 53.005f;
            double d = 2345.7652;
            bool b = true;

            Console.WriteLine(i.ToString());
            Console.WriteLine(f.ToString());
            Console.WriteLine(d.ToString());
            Console.WriteLine(b.ToString());
            Console.ReadKey();
            
        }
    }
}

When the above code is compiled and executed, it produces the following result:

75
53.005
2345.7652
True


Advertisements
Advertisements