English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Type Conversion

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

  • Implicit Type Conversion - These conversions are C# default conversions performed safely, which do not cause data loss. For example, converting from a smaller integer type to a larger integer type, or from a derived class to a base class.

  • Explicit Type Conversion - Explicit type conversion, also known as casting. Explicit conversion requires the casting operator, and casting can result in data loss.

The following example shows an explicit type conversion:

Online Example

namespace TypeConversionApplication
{
    class ExplicitConversion
    {
        static void Main(string[] args)
        {
            double d = 5673.74;
            int i;
            // Explicitly convert double to int
            i = (int)d;
            Console.WriteLine(i);
            Console.ReadKey();
            
        }
    }
}

When the above code is compiled and executed, it will produce the following result:

5673

C# Type Conversion Methods

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

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

The following example demonstrates how to convert different value types to string types:

Online Example

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