Type Casting


When we want to convert one type of value to another type of value that process called type convertion.

C# supports type casting in two way implicit type casting and explicit type casting

Implicit Type Casting: When we are converting smaller type to a higher type then it called an implicit type casting which appens automatically.

Explicit Type Casting: When we are converting higher type to a smaller type then it called an explicit type casting which weneed to do manually.

Implicit Casting

It will automatically convert smaller value to higher data type when we assign, For example

Try it
int samllerValue = 101;
double higherValue = samllerValue;	// Here it will implicit type cast int to double and becomes double types of value
Console.WriteLine(samllerValue);	// It will print 101
Console.WriteLine(higherValue);		// It will also print 101

Explicit Casting

It will be manually converted to smaller value from higher data type when we manually add type encloded in parentheses in front of the value, For example

Try it
double higherValue = 52.89;
int samllerValue = (int)higherValue;	// Here we have added int in front of double type
Console.WriteLine(higherValue);		// It will print 52.89
Console.WriteLine(samllerValue);	// It will print 52

Convert type with Methods

C# also supports built-in methods to convert one data type to another. There is a class named Convert, which has many methods which will help you to convert one data type value to another data type value like .ToString(), .ToBoolean(), .ToInt32(), .ToInt64(), .ToDouble() etc. For example

Try it
string age = "20";
bool isGood = true;
int year = 2020;
double percentage = 89.90;
Console.WriteLine(Convert.ToInt32(age));	// Converted from string to int
Console.WriteLine(Convert.ToInt32(isGood));	// Converted from bool to int
Console.WriteLine(Convert.ToInt32(myDouble));	// Converted from double to int
Console.WriteLine(Convert.ToString(year));	// Converted from int to string


← Previous

Next →