Type conversion or type casting is a common feature in programming levels that allows you to go from one type to another. This is common when converting types to strings for logging or converting to different subclasses to access subclass specific methods. C# offers two types of type casting, explicit and implicit. In this article, we will learn about type casting in C#.
There are two types of ways to explicitly type cast. In these scenarios, we tell the compile explicitly to convert our type even if we lose information. For example, we convert a double to an integer, we will lose precision, but we tell the compiler to cast anyway.
The first way to explicitly convert is to put the following (type)
before the variable you want to cast.
double a = 20.54;
int b = (int)a;
Console.WriteLine(b); // 20
The second type of conversion is implicit. This allows you to convert between a small to larger value, but not the reverse. For example, we can go from an int
to a long
, without explicit conversion, but not the reverse, as we saw above. The follows similar for classes with inheritance.
int a = 20;
long b = a;
double c = a;