Type Conversion & Casting

  • Post author:
Download PDF
Advertisement

Type Conversion & Casting

Type conversion is used when we want to assign the value of one data type to another data type. There are two types of conversion in C#.

  1. Automatic Type Conversion / Implicit Type Conversion
  2. Explicit Type Conversion

Automatic Type Conversion

 If the data types are of the same type (e.g. numeric) then the C# compiler does automatic type conversion. OR when we assign a smaller data type value to bigger data type value C# does automatic type conversion. In C# numeric data types are compatible with each other so in these data type automatic conversion is possible, but when we try to assign a numeric data type to a string type then it is a compile-time error. Because these are not the same. For example, when we assign a Boolean type to a char type then again it’s a compile-time error. C# does not support automatic type conversion in incompatible data types. The numeric type conversion is done in the following order.

byte -> short -> int -> long -> float -> double

The above line explains that a smaller data type can be converted into a bigger data type. But if we try to convert a bigger data type into a smaller one then it will give us a false result. For example, if we try to convert int into long then it will be converted easily because int has 4-bytes size and long has 8-bytes so it is not a problem for long to hold a value of 4-bytes. Now if we convert a long into int then the int will only hold 4-bytes and other 4-bytes will be lost. It will be a compile-time error. This can be achieved by explicit type casting which we’ll discuss after this.

The following table shows the automatic type conversion supported by C#.

Convert From Convert To
byte short, int, long, float, double
short int, long, float, double
int long, float, double
long float, double
float double

Example:

In this example, we’ll see how the automatic type conversion in C#.

   // C# program to demonstrate the 
   // Implicit Type Conversion 
   using System; 
   namespace TypeConversionEXP{ 
  
   class Zitoc { 
  
       // Main Method 
       public static void Main(String []args) 
       { 
          int num1 = 60;  
              
          // automatic type conversion 
          long num2 = num1;  
               
          // automatic type conversion 
          float num3 = num2; 
                     
          // Display Result 
          Console.WriteLine("Int value "  +num1); 
          Console.WriteLine("Long value "  +num2); 
          Console.WriteLine("Float value "  +num3); 
       } 
     } 
   }

Output:

Int value 60

Long value 60

Float value 60

 

Explicit Type Casting

Now let’s see what happens when we try to assign a one data type to another data type in automatic type conversion. This program will result in an error because we are converting a bigger data type into a smaller data type.

Advertisement

   // C# program to illustrate incompatible data  
   // type for explicit type conversion 
   using System; 
   namespace TypeConversionExp2
   { 
      class zitoc
      { 
        // Main Method 
        public static void Main(String []args) 
        { 
          long d = 934.12; 
          // Incompatible Data Type 
          byte b = d;
          // Display Result     
          Console.WriteLine("Value of i is ", +i); 
        } 
      }
   }

Error:

prog.cs(14,21): error CS0266: Cannot implicitly convert type long to byte. An explicit conversion exists (are you missing a cast?)

When we convert a bigger data type to a smaller data type then explicit type casting is required. The main point here is that if we convert a bigger data type to a smaller data type through explicit type conversion than it will result in data loss. It is also called lossy conversion. Let’s explain it through an example.

Example

   // C# program to demonstrate the 
   // Explicit Type Conversion 
   using System; 
   namespace Casting{ 
  
   class GFG
   {
     // Main Method 
     public static void Main(String []args) 
     { 
       double num = 823.78; 
  
       // Explicit Type Casting 
       int num2 = (int)num; 
  
       // Display Result 
       Console.WriteLine("Value of num2 is " +num2); 
     } 
     }
   }

Output:

Value of num2 is 823

It’s a lossy conversion. We have lost 0.78 value.

Below is given a table of methods that C# provides for explicit conversion.

Method Details
ToChar It will convert other types to char type value
ToBoolean It will convert other types to Boolean type value
ToByte It will convert other types to byte type value
ToDouble It will convert other types to double type value
ToString It will convert other types to string type value
ToDecimal It will convert other types to Decimal type value
ToInt16 It will convert other types to 16-bit integer type value
ToInt32 It will convert other types to 32-bit integer type value
ToInt64 It will convert other types to 64-bit integer type value
ToUInt16 It will convert other types to an unsigned 16-bit integer value
ToUInt32 It will convert other types to an unsigned 32-bit integer value
ToUInt64 It will convert other types to an unsigned 64-bit integer value

Example

   // C# program to demonstrate the 
   // Built- In Type Conversion Methods 
   using System; 
   namespace ExplicitTypeCastingExp
   {
     class Zitoc
     {
        // Main Method 
        public static void Main(String []args) 
        { 
            int num1 = 20; 
            double num2 = 871.67; 
            float num3 = 89.1F; 
              
            // Using Built- In Type Conversion 
            // Methods & Displaying Result 
            Console.WriteLine(Convert.ToString(num3)); 
            Console.WriteLine(Convert.ToInt32(num2)); 
            Console.WriteLine(Convert.ToUInt32(num3)); 
            Console.WriteLine(Convert.ToDouble(num1)); 
            Console.WriteLine("Zitoc…!"); 
        } 
      } 
   }

Output:

89.18718920Zitoc…!

Point to Note:

Always remember that when applying explicit conversion in larger to smaller keep in mind that it can cause a logical error. Your output will be changed.

 

Variable as constant

Advertisement