Type casting is required when assign the data of one type of variable to another type of variable. If the types are comparable then C# automatically converts it, if not then type casting is required which the user have to add.
There are two types of type conversions:
1. Implicit Conversion:
This type conversion happens when the two types are comparable or the lower data type is assigned to higher data type.
using System;
class Program{
static void Main(string[] args)
{
// Here Implicit conversion is performed automatically as a gets converted from int to double value.
int a = 10;
double b = a;
}
}
- 2. Explicit Conversion:
When the types are not comparable and automatic conversion cannot be done then it is called explicit conversion. It is also done when a bigger data is type value is being assigned to lower data type.
To perform explicit conversion C# provides built in methods such as,
ToBoolean: It converts the type to boolean value.
ToChar: It converts the type to character value.
ToDecimal: It converts the type to decimal value.
ToDouble: It converts the type to double value.
using System;
class Program{
static public void Main(string[] args)
{
int a = 10;
double b = 12.975;
// ToDouble converts a from int to double.
Console.WriteLine(ToDouble(a));
// ToString converts b from double to string value.
Console.WriteLine(ToString(b));
}
}