C# Type conversion

In C#, type conversion is the process of converting a value of one data type to another data type.

Type conversion in C# can be divided into two types:Implicit type conversionandExplicit type conversion(also known as forced type conversion).

Implicit type conversion

Implicit conversion is a conversion that does not require writing code to specify it; the compiler performs it automatically.

Implicit conversion refers to the fact that when converting a data type with a smaller range to a data type with a larger range, the compiler automatically completes the type conversion. These conversions are C# default conversions performed in a safe manner and do not cause data loss.

For example, from int to long, from float to double, etc.

Converting from a small integer type to a large integer type, or from a derived class to a base class. When assigning a variable of byte type to a variable of int type, the compiler will automatically convert the byte type to int type without requiring explicit conversion.

Example

byte b = 10;
int i = b; // Implicit conversion, no explicit conversion needed

Assigning an integer to a long integer, or assigning a floating-point number to a double-precision floating-point number, this kind of conversion does not cause data loss:

Example

int intValue = 42;
long longValue = intValue; // Implicit conversion from int to long

Explicit conversion

Explicit type conversion, also known as forced type conversion, requires the programmer to explicitly specify it in the code.

Explicit conversion refers to the fact that when converting a data type with a larger range to a data type with a smaller range, or converting one object type to another object type, a cast operator is required for explicit conversion. Forced conversion can cause data loss.

For example, assigning an int type variable to a byte type variable requires explicit conversion.

Example

int i = 10;
byte b = (byte)i; // Explicit conversion, requires a cast operator

Cast to an integer type:

Example

double doubleValue = 3.14;
int intValue = (int)doubleValue; // Force cast from double to int; data may lose the fractional part

Cast to a floating-point type:

Example

int intValue = 42;
float floatValue = (float)intValue; // Forced conversion from int to float, data may lose precision

Cast to a string type:

Example

int intValue = 123;
string stringValue = intValue.ToString(); // Convert int to string

The following example demonstrates an explicit type conversion:

Example

using System;

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 Methods

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

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

These methods are all defined in the System.Convert class, and you need to include the System namespace when using them. They provide a safe way to perform type conversion because they can handle null values and will throw an exception if the conversion is not possible.

For example, using the Convert.ToInt32 method to convert a string to an integer:

string str = "123";
int number = Convert.ToInt32(str); // 转换成功,number为123

If the string is not a valid integer representation, Convert.ToInt32 will throw a FormatException.

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

Example

using System;

namespace TypeConversionApplication
{
    class StringConversion
    {
        static void Main(string[] args)
        {
            // Define an integer variable
            int i = 75;
           
            // Define a floating-point variable
            float f = 53.005f;
           
            // Define a double-precision floating-point variable
            double d = 2345.7652;
           
            // Define a boolean variable
            bool b = true;

            // Convert an integer variable to a string and output it
            Console.WriteLine(i.ToString());
           
            // Convert floating-point variable to string and output
            Console.WriteLine(f.ToString());
           
            // Convert the double-precision floating-point variable to a string and output it
            Console.WriteLine(d.ToString());
           
            // Convert boolean variable to string and output
            Console.WriteLine(b.ToString());

            // Wait for the user to press a key before closing the console window
            Console.ReadKey();
        }
    }
}

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

75
53.005
2345.7652
True

When performing type conversion, the following points need to be noted:

  • Implicit conversion can only convert a data type with a smaller range to a data type with a larger range, and cannot convert a data type with a larger range to a data type with a smaller range;
  • Explicit conversion may cause data loss or reduced precision, so compatibility checks of data types are required;
  • For object type conversion, compatibility checks for type conversion and safety checks for type conversion are required.

Type conversion methods

C# provides various type conversion methods, such as the Convert class, Parse method, and TryParse method, which can help handle conversions between different data types.

Using the Convert class

The Convert class provides a set of static methods that can convert between various basic data types.

Example

string str = "123";
int num = Convert.ToInt32(str);

Using the Parse method

The Parse method is used to convert a string to the corresponding numeric type, and it throws an exception if the conversion fails.

Example

string str = "123.45";
double d = double.Parse(str);

Using the TryParse method

The TryParse method is similar to Parse, but it does not throw an exception; instead, it returns a Boolean value indicating whether the conversion succeeded.

Example

string str = "123.45";
double d;
bool success = double.TryParse(str, out d);

if (success) {
    Console.WriteLine("Conversion successful: " + d);
} else {
    Console.WriteLine("Conversion failed");
}

Custom type conversion

C# also allows you to define custom type conversion operations by defining the implicit or explicit keyword in a type.

Example

using System;

public class Fahrenheit
{
    public double Degrees { get; set; }

    public Fahrenheit(double degrees)
    {
        Degrees = degrees;
    }

    // Implicit conversion from Fahrenheit to double
    public static implicit operator double(Fahrenheit f)
    {
        return f.Degrees;
    }

    // Explicit conversion from double to Fahrenheit
    public static explicit operator Fahrenheit(double d)
    {
        return new Fahrenheit(d);
    }
}

public class Program
{
    public static void Main()
    {
        Fahrenheit f = new Fahrenheit(98.6);
        Console.WriteLine("Fahrenheit object: " + f.Degrees + " degrees");

        double temp = f; // Implicit conversion
        Console.WriteLine("After implicit conversion to double: " + temp + " degrees");

        Fahrenheit newF = (Fahrenheit)temp; // Explicit conversion
        Console.WriteLine("After explicit conversion back to Fahrenheit: " + newF.Degrees + " degrees");
    }
}

In the above example, we defined a Fahrenheit class and implemented an implicit conversion from Fahrenheit to double and an explicit conversion from double to Fahrenheit.

The output result will be displayed as follows:

Fahrenheit object: 98.6 degrees
After implicit conversion to double: 98.6 degrees
After explicit conversion back to Fahrenheit: 98.6 degrees

Summary

In C#, built-in type conversion methods are mainly implemented in the following ways: implicit conversion, explicit conversion (forced conversion), methods using the Convert class, the Parse method, and the TryParse method. These methods are widely used for conversion between different data types.

The following is a table of C# built-in type conversion methods:

Method categoryMethodsDescription
Implicit conversionAutomatic conversionNo explicit specification is required; it is usually used for safe type conversions, such as from a smaller type to a larger type.
Explicit conversion (cast)(type)valueExplicit specification is required; it is usually used in cases that may cause data loss or conversion failure.
ConvertClass methodsConvert.ToBoolean(value)Converts the specified type toBoolean
Convert.ToByte(value)Converts the specified type toByte
Convert.ToChar(value)Converts the specified type toChar
Convert.ToDateTime(value)Converts the specified type toDateTime
Convert.ToDecimal(value)Converts the specified type toDecimal
Convert.ToDouble(value)Converts the specified type toDouble
Convert.ToInt16(value)Converts the specified type toInt16(short integer)
Convert.ToInt32(value)Converts the specified type toInt32(integer)
Convert.ToInt64(value)Converts the specified type toInt64(long integer)
Convert.ToSByte(value)Converts the specified type toSByte
Convert.ToSingle(value)Converts the specified type toSingle(single-precision floating-point type)
Convert.ToString(value)Converts the specified type toString
Convert.ToUInt16(value)Converts the specified type toUInt16(unsigned short integer type)
Convert.ToUInt32(value)Converts the specified type toUInt32(unsigned integer)
Convert.ToUInt64(value)Converts the specified type toUInt64(unsigned long integer type)
ParseMethodsBoolean.Parse(string)Parse the string asBoolean
Byte.Parse(string)Parse the string asByte
Char.Parse(string)Parse the string asChar
DateTime.Parse(string)Parse the string asDateTime
Decimal.Parse(string)Parse the string asDecimal
Double.Parse(string)Parse the string asDouble
Int16.Parse(string)Parse the string asInt16
Int32.Parse(string)Parse the string asInt32
Int64.Parse(string)Parse the string asInt64
SByte.Parse(string)Parse the string asSByte
Single.Parse(string)Parse the string asSingle
UInt16.Parse(string)Parse the string asUInt16
UInt32.Parse(string)Parse the string asUInt32
UInt64.Parse(string)Parse the string asUInt64
TryParseMethodsBoolean.TryParse(string, out bool)Try to parse the string asBoolean, returns a Boolean value indicating whether it succeeded
Byte.TryParse(string, out byte)Try to parse the string asByte, returns a Boolean value indicating whether it succeeded
Char.TryParse(string, out char)Try to parse the string asChar, returns a Boolean value indicating whether it succeeded
DateTime.TryParse(string, out DateTime)Try to parse the string asDateTime, returns a Boolean value indicating whether it succeeded
Decimal.TryParse(string, out decimal)Try to parse the string asDecimal, returns a Boolean value indicating whether it succeeded
Double.TryParse(string, out double)Try to parse the string asDouble, returns a Boolean value indicating whether it succeeded
Int16.TryParse(string, out short)Try to parse the string asInt16, returns a Boolean value indicating whether it succeeded
Int32.TryParse(string, out int)Try to parse the string asInt32, returns a Boolean value indicating whether it succeeded
Int64.TryParse(string, out long)Try to parse the string asInt64, returns a Boolean value indicating whether it succeeded
SByte.TryParse(string, out sbyte)Try to parse the string asSByte, returns a Boolean value indicating whether it succeeded
Single.TryParse(string, out float)Try to parse the string asSingle, returns a Boolean value indicating whether it succeeded
UInt16.TryParse(string, out ushort)Try to parse the string asUInt16, returns a Boolean value indicating whether it succeeded
UInt32.TryParse(string, out uint)Try to parse the string asUInt32, returns a Boolean value indicating whether it succeeded
UInt64.TryParse(string, out ulong)Try to parse the string asUInt64, returns a Boolean value indicating whether it succeeded
other extensions