C# Type Conversion Tutorial For Beginners With Examples

C# allows converting one data type to another data type. This process is called as Type Conversion.
Type Conversion is useful in many scenarios. For instance there may be a requirement to pass integer data to a method which accepts only string data. In this case type conversion happens.
Type conversions are of following types:
  • Implicit Conversions
  • Explicit Conversions

Implicit Conversions in C#

If conversion from one type to another type can occur without any data loss then C# performs an implicit conversion.
Below is an example of an implicit conversion performed by C#. In this example int which is a 32-bit integer type is safely converted to long which is a 64-bit integer type.
   
    class Program 
    {
        static void Main(string[] args)
        {
            long longData;
            int intData = 643;

            longData = intData;

            System.Console.WriteLine(longData);            
            System.Console.ReadLine();
        } 
    }
   
Output of the above program will be 643
Conversion from derived class to base class happens implicitly.

Explicit Conversions in C#

If there is a risk of losing data while converting from one type to another then the data type has to be explicitly converted. This process is known as Explicit conversion or Casting.
Below is an example of explicit conversion performed by C#. In this example double which is a 64-bit floating type is converted explicitly to int which is a 32-bit integer type.
   
    class Program 
    {
        static void Main(string[] args)
        {
            double doubleData = 93451.65;

            int intData;

            intData = (int)doubleData;

            System.Console.WriteLine(intData);            
            System.Console.ReadLine();
        } 
    }
   
Output of the above program will be 93452
A base class has to be explicitly converted to a derived class.
C# also provides different type of conversion functions in System.Convert static class. This class has methods like ToInt32, ToSingle, ToChar etc. to do the explicit conversions.

Boxing and Unboxing

The concept of boxing and unboxing highlights the fact that a value of any type can be treated as an object.
Boxing
The process of converting a value type to the type System.Object is known as Boxing.
This type of conversion always happens implicitly.
 
    int intData = 36; //Value Type

    object oData; //Object Type

    oData = intData; //Boxing

Unboxing
The process of converting a System.Object type to a value type is known as Unboxing.
This type of conversion always happens explicitly.
 
    int intData = 36; //Value Type

    object oData; //Object Type

    oData = intData; //Boxing

    int intValueData = (int)oData; //Unboxing