Type casting is a way to convert a value from one data type to another in C#. There are two types of type casting in C#.
Implicit type casting is done automatically by the compiler when there is no possibility of losing data in the conversion. It works as converting a smaller type to a larger type size.
int myInt = 12; double myDouble = myInt; // Automatic casting: int to double Console.WriteLine(myInt); // Outputs 12 Console.WriteLine(myDouble); // Outputs 12
Explicit type casting is done by the programmer when there is a possibility of losing data in the conversion. It works as converting a larger type to a smaller type size.
double myDouble = 12.68; int myInt = (int) myDouble; // Programmer casting: double to int Console.WriteLine(myDouble); // Outputs 12.68 Console.WriteLine(myInt); // Outputs 12
when we explicitly cast a value to a smaller data type, there is a possibility of losing data or precision. In this case, the compiler truncates the value to fit into the smaller data type, which can result in a loss of information.
float num1 = 10.5f; int num2 = (int)num1; // num1 is explicitly cast to intOutput- 10