How to Use Implicit and Explicit Casting - C#

When you want to convert a value from one data type to another data type, you need to cast it.

There are two types of casting in C#:

  • Implicit casting - When you convert a smaller type, to a larger type.
  • Explicit casting - When you convert a larger type, to a smaller type.

How to implicitly cast

Implicit casting is done automatically, as converting a value to a larger type doesn't lose any definition.

For example, if we cast from an int to a float:

int anInt = 12;
float aFloat = anInt;

Here, the float variable is simply assigned to the value of the integer.

If we print both values, we can see they are the same:

Console.WriteLine($"anInt: {anInt}");
Console.WriteLine($"aFloat: {aFloat}");
anInt: 12
aFloat: 12

How to explicitly cast

Explicit casting is a manual process, as we need to specify the type we are casting to, before assigning the variable.

For example, if we cast back from a float to an int:

float aFloat = 12.945f;
int anInt = (int) aFloat;

Since an integer cannot store a value of 12.345, casting the value to an int will result in the decimal values being lost.

We can see this when printing both values:

Console.WriteLine($"aFloat: {aFloat}");
Console.WriteLine($"anInt: {anInt}");
aFloat: 12.945
anInt: 12