Latest web development tutorials

C # type conversion

Type conversion from type casting is fundamentally, or that convert data from one type to another type. In C #, type casting in two forms:

  • Implicit type conversion - these conversions are C # default conversion carried out in a safe manner.For example, small integer type to a larger integer type, conversion from a derived class to the base class.
  • Explicit type conversion - these conversions are using predefined functions through the user explicitly done.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 results:

5673

C # type conversion

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

序号方法 & 描述
1ToBoolean
如果可能的话,把类型转换为布尔型。
2ToByte
把类型转换为字节类型。
3ToChar
如果可能的话,把类型转换为单个 Unicode 字符类型。
4ToDateTime
把类型(整数或字符串类型)转换为 日期-时间 结构。
5ToDecimal
把浮点型或整数类型转换为十进制类型。
6ToDouble
把类型转换为双精度浮点型。
7ToInt16
把类型转换为 16 位整数类型。
8ToInt32
把类型转换为 32 位整数类型。
9ToInt64
把类型转换为 64 位整数类型。
10ToSbyte
把类型转换为有符号字节类型。
11ToSingle
把类型转换为小浮点数类型。
12ToString
把类型转换为字符串类型。
13ToType
把类型转换为指定类型。
14ToUInt16
把类型转换为 16 位无符号整数类型。
15ToUInt32
把类型转换为 32 位无符号整数类型。
16ToUInt64
把类型转换为 64 位无符号整数类型。

The following examples of the different types of value are converted 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 results:

75
53.005
2345.7652
True