The C#type conversion

Type conversion is essentially type casting, or the conversion of data from one type to another. There are two forms of type casting in C#:

  • Implicit type conversions - These conversions are the default and secure conversions for C#. For example, convert from a small integer type to a large integer type, from a derived class to a base class.
  • Explicit type conversions - These conversions are done explicitly by the user using predefined functions. Explicit conversions require cast operators.

The following example shows an explicit type conversion:

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

            // 强制转换 double 为 int
            i = (int)d;
            Console.WriteLine(i);
            Console.ReadKey();
            
        }
    }
}

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

5673

The C#type conversion method

The following built-in type conversion methods are available for C#:

Serial number Method & Description
1 ToBoolean
Convert the type to a Boolean if possible.
2 ToByte
Convert type to byte type.
3 ToChar
If possible, convert the type into a single Unicode character type.
4 ToDateTime
Convert the type (integer or string type) into a date-time structure.
5 ToDecimal
Convert floating point or integer type to a decimal type.
6 ToDouble
Convert the type to a double precision floating point.
7 ToInt16
Convert type to 16-bit integer type.
8 ToInt32
Convert the type to a 32-bit integer type.
9 ToInt64
Convert the type to a 64-bit integer type.
10 ToSbyte
Convert the type to a symbolic byte type.
11 ToSingle
Convert type to small float.
12 ToString
Convert the type to a string type.
13 ToType
Convert the type to the specified type.
14 ToUInt16
Convert type to 16-bit unsigned integer type.
15 ToUInt32
Convert the type to a 32-bit unsigned integer type.
16 ToUInt64
Convert the type to a 64-bit unsigned integer type.

The following example converts the types of different values to string types:

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 results:

75
53.005
2345.7652
True