Typecasting in C# is the process of converting a value of one data type to another. This is also known as type conversion.
There are two types of typecasting in C#:
- Implicit typecasting: This is done by the compiler automatically when a smaller data type is assigned to a larger data type. For example:
int num = 10; double d = num; // implicit typecasting
In the above example, the integer variable “num” is assigned to a double variable “d”. Since double is a larger data type than int, the compiler automatically converts the value of “num” to a double.
- Explicit typecasting: This is done by the programmer using an explicit cast operator. It is necessary when converting a larger data type to a smaller data type, or when converting between different data types that are not directly compatible. For example:
double d = 10.5; int num = (int)d; // explicit typecasting
In the above example, the double variable “d” is assigned to an integer variable “num”. Since int is a smaller data type than double, we need to use an explicit cast operator to convert the value of “d” to an int.
Note that explicit typecasting can result in data loss or other unexpected behavior, so it should be used with caution.