C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# type conversion



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

  • #Implicit type conversions - These conversions are C#'s default conversions that are performed in a safe manner. For example, converting from a small integer type to a large integer type, and from a derived class to a base class.

  • Explicit Type Conversions - These conversions are done explicitly by the user using predefined functions. Explicit conversion requires 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;

            // 强制转换 double 为 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 method

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

##Serial numbermethod & Description12345678910111213141516
ToBooleanConvert the type to Boolean if possible.
ToByteConvert the type to byte type.
ToCharConvert the type to a single Unicode character type if possible.
ToDateTimeConvert the type (integer or string type) to a date-time structure.
ToDecimalConvert floating point or integer type to decimal type.
ToDouble Convert the type to double precision floating point.
ToInt16Convert the type to a 16-bit integer type.
ToInt32Convert the type to a 32-bit integer type.
ToInt64Convert the type to a 64-bit integer type.
ToSbyteConvert the type to a signed byte type.
ToSingle Convert the type to a small floating point number type.
ToString Convert the type to string type.
ToTypeConvert the type to the specified type.
ToUInt16Convert the type to a 16-bit unsigned integer type.
ToUInt32Convert the type to a 32-bit unsigned integer type.
ToUInt64Convert the type to a 64-bit unsigned integer type.
The following example converts different value types into 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 will produce the following Result:

75
53.005
2345.7652
True