Curriculum
Typecasting in C# is the process of converting a value of one data type to another data type. In C#, typecasting can be done implicitly or explicitly.
Implicit typecasting is done automatically by the compiler when the conversion is safe and lossless, while explicit typecasting requires the use of typecasting operators and can result in a loss of data.
Here is an example of implicit typecasting:
int num1 = 10; float num2 = num1; // implicit typecasting from int to float
In this example, the value of num1
is implicitly cast to a float
value and stored in num2
. Since the conversion is safe and lossless, the compiler performs this typecasting automatically.
Here is an example of explicit typecasting:
float num1 = 10.5f; int num2 = (int)num1; // explicit typecasting from float to int
In this example, the value of num1
is explicitly cast to an int
value using the typecasting operator (int)
. Since the conversion is not lossless, the compiler requires that this typecasting is performed explicitly.
It’s important to note that explicit typecasting can result in a loss of data, so it should be used with caution. Here’s an example of what can happen when typecasting is not done properly:
int num1 = 1000; byte num2 = (byte)num1; // explicit typecasting from int to byte Console.WriteLine(num2); // Output: 232
In this example, the value of num1
is explicitly cast to a byte
value. Since the byte
data type can only store values between 0 and 255, the value of num2
is truncated to fit this range. As a result, the output is 232 instead of 1000.
Typecasting is a powerful tool in C# programming, but it must be used carefully to avoid data loss and other issues.