Typecasting in C#

Posted by

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#:

  1. 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.

  1. 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.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.