Understanding Type Casting or Type Conversion in C#

Understanding Type Casting or Type Conversion in C#

23 May 2024
Intermediate
152K Views
9 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

Type casting: An Overview

Type Casting or Type Conversion is a mechanism to convert one data type value to another one. Type conversion is possible if both the data types are compatible to each other; otherwise, you will get an InvalidCastException. In this C# Tutorial, we will explore more about Typecasting which will include Implicit conversion vs Explicit conversion vs User-defined conversion, different types of type casting or type conversions, and last but not least What the Upcasting and Downcasting. First Let's see the difference between Implicit conversion, Explicit conversion, and User-defined conversion.

Implicit vs Explicit vs User-defined.

Implicit conversionExplicit ConversionUser-Defined Conversion
It is also known as automatic conversion, which occurs when the compiler automatically converts one data type into another without requiring any explicit instructions from the programmer.It is also known as type casting or type conversion, requires the programmer to explicitly specify the conversion from one data type to anotherIt allows developers to define their own rules for converting between data types that are not natively supported by the language.
It happens when the destination data type can accommodate all possible values of the source data type without loss of information or precision.This is done using language-provided conversion functions or syntax.It is achieved by overloading operators or defining conversion functions within user-defined types.

Example: Implicit conversion from int to double

int intValue = 22;

double doubleValue = intValue;

Example: Explicit conversion from double to int

double doubleValue = 22.5;

int intValue = (int)doubleValue;

Example: Explicit user-defined conversion from MyType to int

MyType myObj = new MyType(10); int intValue = (int)myObj;

Different Types of Type Casting or Type Conversion

  1. Implicit conversion

    Implicit conversion is being done automatically by the compiler and no data will be lost. It includes the conversion of a smaller data type to a larger data type and the conversion of derived classes to base class. This is a safe type of conversion. Let's elaborate on this in the real-world example in C# Compiler.

     using System;
    
    public class Program
    {
    	public static void Main()
    	{
    		int i = 444;
    		double d1 = i; // Implicit casting from int to double
    
    		int i1 = 55;
    		// automatic type conversion
    		long l = i1;
    		float f = l;
    		
    		char i2 = '0';
    		int d2 = i2;
    
    		
    		Console.WriteLine($"d1 = {d1}"); 
    		Console.WriteLine($"l = {l}"); 
    		Console.WriteLine($"f = {f}"); 
    		Console.WriteLine($"d2 = {d2}"); 
    	}
    }
        

    Output

    d1 = 444
    l = 55
    f = 55
    d2 = 48
  2. Explicit conversion

    Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or the conversion might not succeed for some reason. This is an unsafe type of conversion.

     using System;
    
    public class Program
    {
    	public static void Main()
    	{
    		long l = 2222;
    		int i = (int)l; 
    		double d = 143.78;
    		int i1 = (int)d;   
    		
    		double d1 = 342.78;
    		float f = (float)d1;
    		decimal dec = (decimal)d1;
    
    		
    		Console.WriteLine($"i = {i}"); 
    		Console.WriteLine($"i1 = {i1}"); 
    		Console.WriteLine($"f = {f}"); 
    		Console.WriteLine($"dec = {dec}"); 
    		
    	}
    }
    

    Output

     i = 2222
    i1 = 143
    f = 342.78
    dec = 342.78
    
  3. User-defined conversion

    User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to struct or basic data type and struct to class or basic data type. Also, all conversion methods must be declared as static.

     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;
     }
    
    }
    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;
     }
    }   

Read More - C Sharp Interview Questions

What is the Upcasting and Downcasting?

There are two more casting terms Upcasting and Downcasting. basically, these are parts of Implicit conversion and Explicit conversion.

Implicit conversion of derived classes to base classes is called Upcasting and Explicit conversion of base class to derived classes is called Downcasting.

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

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

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

 Base b2 = new Base();
 //Downcasting
 Derived d2 = (Derived)b2; 
 }
}
    
What do you think?

I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Also, Consider our C# Programming Course for a better understanding of all C# concepts

FAQs

Q1. What is type casting and type conversion in C#

When the variable of one data type is changed to another data type is known as the Type Casting. According to our needs, we can change the type of data. At the time of the compilation, C# is a statically-typed i.e., after the declaration of the variable, we cannot declare it again

Q2. What is C# type conversion?

Type conversion in C# is the process of converting a value of one data type to another data type.

Q3. Why type conversion is used?

Type casting, also known as type conversion, is an important concept in Java that allows us to convert one data type into another.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingNov 08MON, TUE, WED, THU, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Developer Certification TrainingNov 09SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingNov 09SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingNov 10SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Angular Certification TrainingNov 17SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Software Architecture and Design TrainingNov 24SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
.NET Solution Architect Certification TrainingNov 24SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this