Type Casting in C#

Type Casting in C# with Examples

In this article, I am going to discuss Type Casting in C# with Examples. Please read our previous article, where we discussed Literals in C# with Examples. At the end of this article, you will understand what Type Casting is and why and when we need Type Casting in C#.

What is Type Casting in C#?

In simple words, we can say that Type Casting or Type Conversion in C# is the process to change one data type into another data type. The Type Conversion in C# is only possible if both the data types are compatible with each other else we will get InvalidCastException.

According to our business needs, we can change the type of data. At the time of the compilation, C# followed statically-typed i.e., after the declaration of a variable, we cannot declare it again. Again, the value of the variable cannot be assigned to another type of variable unless we change the type of the variable.

Let us understand this with an example. Here, we are creating a variable of int data type. We cannot convert the string value implicitly to the int. Therefore, if we declare the variable ‘a’ as int, we cannot assign the string value “Hello” to it.

int a;

a = “Hello”; // error CS0029: we cannot implicitly convert string type’ to ‘integer’ type

However, we can face a situation when there is a need to copy the value of one variable into another variable or a method parameter of another type. For example, we have a variable integer, and we need to pass it to a method parameter whose type is double. Or the situation can be to assign the class variable to the variable of the type of interface. These types of operations are called Type Conversion.

So, the process of converting the value of one data type (int, float, double, etc.) to another data type ((int, float, double, etc.)) is known as type conversion or typecasting.

Types of Type Casting in C#

The type conversion or typecasting is done automatically by the compiler or even as a developer we can do it explicitly and hence type casting in C# is classified into two types. They are as follows:

  1. Implicit Type Casting
  2. Explicit Type Casting
Implicit Conversion or Implicit Type Casting / Automatic Type Conversion in C#

The Implicit Conversion or Implicit Type Casting in C# is automatically done by the compiler and in this case, there will be no data loss. Here, the typecasting or type conversion is done from a smaller data type to a larger data type and from derived classes to the base class. This type of type conversion is safe.

In implicit Type Conversion, the compiler will automatically convert one type to another. Generally, in the case of implicit Type Conversion, the smaller data types like int (having less memory size) are automatically converted to larger data types like double (having larger memory size).

Implicit Type Casting happens when:

  1. The two data types are compatible.
  2. When we assign a value of a smaller data type to a bigger data type.

For example, in C#, the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other. Before converting, the compiler first checks the compatibility, and then it decides whether it is good to convert alright or throw some error.

The following diagram shows the implicit types of conversion that are supported by C#:

implicit types of conversion that are supported by C#

Example to Understand Implicit Conversion or Implicit Type Casting in C#

Let us understand implicit Type Conversion with an example. In the below example, we have created an int-type variable with the name numInt. Please notice the line, double numDouble = numInt; Here, we are assigning the int type variable value to a double type variable. In this case, the compiler will automatically convert the int type value to double. Also, here we have used the GetType() method to check the type of numInt and numDouble variables data type.

using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int numInt = 1500;

            // get type of numInt
            Type n = numInt.GetType();

            // Implicit Conversion
            double numDouble = numInt;

            // get type of numDouble
            Type n1 = numDouble.GetType();

            // Value Before Conversion
            Console.WriteLine("numInt value: " + numInt);
            Console.WriteLine("numInt Type: " + n);

            // Value After Conversion
            Console.WriteLine("numDouble value: " + numDouble);
            Console.WriteLine("numDouble Type: " + n1);
           
            Console.ReadKey();
        }
    }
} 
Output:

Example to Understand Implicit Conversion or Implicit Type Casting in C#

Note: In implicit type conversion, smaller types are converted to larger types. Hence, there is no loss of data during the conversion.

Implicit Conversion Example in C# using Derived Type
using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Derived derived = new Derived();
            //Implicit Type Conversion
            Base b = derived;
        }
    }
    class Base
    {
        public int Num1 { get; set; }
    }

    class Derived : Base
    {
        public int Num2 { get; set; }
    }
}
Explicit Conversion or Explicit Type Casting in C#

Explicit Conversion or Explicit Type Casting in C# is done by using the Cast operator. It includes conversion of larger data types to smaller data types and conversion of base classes to derived classes. In the case of Explicit Conversion or Explicit Type Casting there is a chance that data might be lost or conversion might not be succeeded for some reason. This is an unsafe type of conversion.

In Explicit Type Conversion, we explicitly convert one data type to another data type. In this case, the larger data types like double (having large memory size) are converted to smaller data types like int (having small memory size).

Example to Understand Explicit Conversion or Explicit Type Casting in C#

There may be some compilation errors when types are not compatible with each other. For example, assigning a double value to an int data type results in a compile-time error,

using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            double numDouble = 1.23;

            // Explicit Type Casting
            int numInt = numDouble;

            // Value Before Conversion
            Console.WriteLine("Original double Value: " + numDouble);

            // Value After Conversion
            Console.WriteLine("Converted int Value: " + numInt);
            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Explicit Conversion or Explicit Type Casting in C#

So, if we want to assign a value of a larger data type to a smaller data type then we need to perform explicit type casting in C#. This is useful for incompatible data types where automatic type conversion is not possible by the compiler.

In the below example, we have created a double variable named numDouble. Notice the line, int numInt = (int)numDouble; Here, (int) is a cast expression that explicitly converts the double type to int type.

using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            double numDouble = 1.23;

            // Explicit Type Casting
            int numInt = (int)numDouble;

            // Value Before Conversion
            Console.WriteLine("Original double Value: " + numDouble);

            // Value After Conversion
            Console.WriteLine("Converted int Value: " + numInt);
            Console.ReadKey();
        }
    }
}
Output:

Explicit Conversion or Explicit Type Casting in C#

Here, you can see that the original value is 1.23 whereas the converted value is 1. That means we have lost some data during the type conversion. This is because we are explicitly converting the larger data type double to smaller type int.

Explicit Conversion Example in C# using Derived Type
using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Base b = new Base();
            //Explicit Type Conversion
            Derived derived = (Derived)b;

            Console.ReadKey();
        }
    }

    class Base
    {
        public int Num1 { get; set; }
    }

    class Derived : Base
    {
        public int Num2 { get; set; }
    }
}
User-Defined Conversion or User-Defined Type Casting in C#

The User-Defined Conversion or User-Defined Type Casting in C# is performed by using special methods that we can define to enable explicit and implicit conversions. It includes conversion of class to a struct or basic data type and struct to class or basic data type. The most important point that you need to remember is all the conversion methods must be declared as static.

Example to User-Defined Conversion or User-Defined Type Casting in C#
using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Implicit Conversion from int to rational number 
            RationalNumber rational1 = 23;

            //Explicit Conversion from rational number to float
            RationalNumber rational2 = new RationalNumber(3, 2);
            float d = (float)rational2;

            Console.ReadKey();
        }
    }

    class RationalNumber
    {
        int numerator;
        int denominator;
        public RationalNumber(int num, int den)
        {
            numerator = num;
            denominator = den;
        }

        public static implicit operator RationalNumber(int i)
        {
            // Rational Number equivalant of an int type has 1 as denominator
            RationalNumber rationalnum = new RationalNumber(i, 1);
            return rationalnum;
        }

        public static explicit operator float(RationalNumber r)
        {
            float result = ((float)r.numerator) / r.denominator;
            return result;
        }
    }
}
Conversion with the helper class in C#: 

For the conversion of the non-compatible type like integer and System.DateTime objects or hexadecimal strings and byte arrays, we can use System.BitConversion class, System.Convert class and the Parse methods of the built-in numeric type like as int32 Parse. C# provides built-in methods for Type-Conversions as follows:

Conversion with the helper class in C#

Example to demonstrate the Built-In Type Conversion Methods in C#:
using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            double d = 123.45;
            float f = 45.678F;

            // Using Built- In Type Conversion Methods & Displaying Result
            Console.WriteLine(Convert.ToString(f));
            Console.WriteLine(Convert.ToInt32(d));
            Console.WriteLine(Convert.ToUInt32(f));
            Console.WriteLine(Convert.ToDouble(i));
            Console.ReadKey();
        }
    }
}
Output:

Example to demonstrate the Built-In Type Conversion Methods in C#

Type Conversion using Parse() Method in C#

In C#, we can also use the built-in Parse() method to perform type conversion. So, while performing type conversion between non-compatible types like int and string, we use Parse() method. Let us understand this with an example.

using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "100";

            //Converting string to int type
            int i = int.Parse(str);
            Console.WriteLine("Original string value: " + str);
            Console.WriteLine("Converted int value: " + i);
            Console.ReadKey();
        }
    }
}
Output:

Type Conversion using Parse() Method in C#

In the above example, we have converted a string type to an int type. The following line of code does the same.

int a = int.Parse(n);

Here, the Parse() method converts the numeric string 100 to an integer value. But we cannot use the Parse() method to convert a textual string like “hello” to an int. In that case, we will get a runtime error. For a better understanding, please have a look at the below example.

using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello";

            //Converting string to int type
            int i = int.Parse(str);
            Console.WriteLine("Original string value: " + str);
            Console.WriteLine("Converted int value: " + i);
            Console.ReadKey();
        }
    }
}

Output: Here, we will not get any compile-time error. We will get the following runtime error.

What is the Upcasting and Downcasting in C#?

What is the Upcasting and Downcasting in C#?

There are two more casting terms used i.e. Upcasting and Downcasting. These are parts of Implicit Conversion and Explicit Conversion. Implicit conversion of derived classes to the base class is called Upcasting and Explicit conversion of base class to derived classes is called Downcasting. For a better understanding, please have a look at the below example.

using System;
namespace TypeCastingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Derived d1 = new Derived();
            //Upcasting
            Base b1 = d1;

            Base b2 = new Base();
            //Downcasting
            Derived d2 = (Derived)b2;
        }
    }

    class Base
    {
        public int Num1 { get; set; }
    }

    class Derived : Base
    {
        public int Num2 { get; set; }
    }
}

In the next article, I am going to discuss Operators in C# with Examples. Here, in this article, I try to explain Type Casting in C# with Examples and I hope you enjoy this Type Casting in C# article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.