C# Type Conversion

While writing code programmers work with various types of data types like string, integer, floats etc. Sometimes there is the requirement to assign the value of one data type to another type.

This process of converting the value of one data type to another is known as ‘type casting’ or ‘type conversion.’ In C# provides ways for type casting.

  1. Implicit Type Conversion:

In implicit type conversion, there is no need to write some special code to convert one type variable to another. The conversion is done automatically by the compiler. This is type-safe casting. In implicit type conversion, no data will be lost.

For built-in types, this type of conversion works if below conditions are fulfilled:

  • The types of two variables must be compatible.
  • The destination type in which we are going to store value after casting must have the higher range than source type.

For example,

using System; 
namespace ImplicitTypeConversion 
{ 
    class Program 
    { 
         static void Main(string[] args) 
         { 
              int num1 = 637893; 
              long num2 = num1;    //Implicit type conversion 
              Console.WriteLine("The value of variable num1 is {0}", num1); 
              Console.WriteLine("The value of variable num2 is {0}", num2); 
              Console.ReadLine();  
         } 
    } 
}


The output of above program is: 

The value of variable num1 is 637893 
The value of variable num2 is 637893

In the case of reference types, an implicit conversion works if destination type is the base class and source type is derived class.

Recommended Post   C# Boxing and Unboxing

For example,

using System; 
namespace ImplicitTypeConversion 
{ 
    class Parent //Base class 
    { 
        public void Display() 
        { 
             Console.WriteLine("This is Parent class method."); 
         } 
    }
   class Child : Parent //Derived class 
   {
       public void Show() 
       { 
          Console.WriteLine("This is Child class method."); 
       } 
   }
   class Program
   { 
       static void Main(string[] args) 
       { 
          Child C = new Child(); 
          Parent P = C;   // Implicit type conversion 
          P.Display(); 
          Console.ReadLine(); 
       } 
    } 
}

The output of above program is:

This is Parent class method.

Following table show possible implicit conversion in C# 

Source Data Type Destination Data Type
char int,uint,logn,ulong, float, double, decimal,ushort
int float,long, double, decimal
uint float,long,ulong,double, decimal
long float,double,decimal
ulong float,double, decimal
float double
sbyte int, long, float, double, decimal, short
byte ushort, short,uint,int, float, long,ulong, decimal, double
short float,int, long, double, decimal
ushort float,uint,int, double, long,ulong, decimal


2. Explicit Type
Conversion:

If types are incompatible then for conversion we use the cast. The cast is the instruction that instructs the compiler to convert data types explicitly. In explicit type conversion, cast operators are used for conversion. Explicit type conversion is unsafe conversion and data might be lost sometimes. The general syntax for this type conversion is as below

(<Target Data Type>) variable (or value);

Here target data type is data type in which we are going to convert the variable.

Recommended Post   C# programming language

For example,  

using System; 
namespace ExplicitTypeConversion 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        {
            double num1 = 56.88; 
            int num2; 
            num2 = (int)num1;   //Explicitly converting double to int
            Console.WriteLine("The value of variable num1 is {0}",num1); 
            Console.WriteLine("The value of variable num2 is {0}", num2); 
            Console.ReadLine(); 
        } 
    } 
}

The output of above program is: 

The value of variable num1 is 56.88 
The value of variable num2 is 56

Following table show possible explicit conversion in C#

Source Data Type Destination Data Type
char short,sbyte, byte
int char,uint,ulong, short,ushort,sbyte, byte
uint char,int, short,ushort,sbyte, byte
long char,int,uint,ulong, short,ushort,sbyte, byte
ulong char,int,uint,long, short,ushort,sbyte, byte
float char,int,unint, long,ulong, short,ushort,sbyte, byte, decimal
sbyte char,byte,uint, long,ushort
byte char,sbyte
short char,uint,ulong,ushort,sbyte, byte
ushort char,short,sbyte, byte

We can also use following way for type conversion;

  • Parsing:

In parsing string value is converted into another primitive value types. In this conversion Parse () method is used which takes the string as an argument and called with value type using dot operator. If the string value is not convertible to value type then Parse() method throws a runtime exception.

For example, 

using System; 
namespace ParsingDemo 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            string str1 = "100"; 
            string str2 = "ABC";
            int num = int.Parse(str1); 
            Console.WriteLine("The value of num is {0}", num); 
            // num = int.Parse(str2); // This line generate runtime error 
            Console.ReadLine(); 
        }
     } 
}

The output of above program is: 
The value of num is 100

  • Convert Class:
Recommended Post   C# Case Control Structure

C# also provides Convert class for conversion. Convert class has various static methods for conversion like ToInt32(), ToString(),  ToDateTime() etc.

using System; 
namespace ConvertClassDemo 
{ 
    class Program
    { 
         static void Main(string[] args) 
         { 
             string str = "120"; 
             int num = Convert.ToInt32(str); 
             Console.WriteLine("The value of num is {0}",num); 
             Console.ReadLine(); 
         }
     } 
}

The output of above program is: 

The value of num is 120
Content Protection by DMCA.com