What Is Type Casting In C#?

3 mins read

Type casting is when you assign a value of one data type to another type.

Because C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or assigned a value of another type unless that type is implicitly convertible to the variable’s type. For instance, the string cannot be implicitly converted to int. Therefore, after you declare i as an int, you cannot assign the string “Hello” to it.

However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions. 

Credit: Code Stones

Types Of Casting In C#

  • Implicit Casting: This type of casting is done automatically when converting a smaller size type to a larger size type: char  -> int  -> long  -> float  -> double

Code Sample of an Implicit Casting:


  • Explicit Casting: This type of casting is done manually by placing the type in parentheses in front of the value: double  -> float  -> long  -> int  -> char

Code Sample:


Type Conversion Methods

It is also possible to convert data types explicitly by using the built-in methods, like: Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32  ( int) and Convert.ToInt64  ( long).

Code Sample:


Why do we require type conversion operation?

We use the type conversion because the type conversion happens when we assign the value of one data type to another. If the data types are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to be converted explicitly, which is known as Explicit Type conversion. For instance, assigning an int  value to a long variable.

The main idea behind type conversion is to make variable of one type compatible with variable of another type to perform an operation.


Thanks for reading…

Happy Coding!

Leave a Reply

Your email address will not be published.