SoFunction
Updated on 2025-03-06

Detailed explanation of 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 done in a safe manner and do not cause data loss. For example, convert from a small integer type to a large integer type, and from a derived class to a base class.
  • Explicit type conversion - Explicit type conversion, i.e. cast type conversion. Explicit conversion requires a cast operator, and casting can cause data loss.

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;
      (i);
      ();
      
    }
  }
}

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

The following example converts different values ​​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;

      (());
      (());
      (());
      (());
      ();
      
    }
  }
}

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

75
53.005
2345.7652
True

The above is the detailed explanation of C# type conversion. For more information about C# type conversion, please pay attention to my other related articles!