C# Type Casting

C# is a strongly typed language, which means that every variable must have a declared type. Type casting refers to the process of converting a variable from one data type to another. There are two types of type casting: implicit and explicit.

Implicit Type Casting

Implicit type casting, also known as type promotion, is an automatic conversion of a smaller data type to a larger data type. This is because the smaller data type can fit into the larger data type without losing any information. For example:

1int num = 10; 2double dblNum = num; //implicit type casting

In the above code, the integer variable num is being converted to a double variable dblNum using implicit type casting.

Explicit Type Casting

Explicit type casting, also known as type conversion, is a manual conversion of a larger data type to a smaller data type. This is because the larger data type cannot fit into the smaller data type without losing information. For example:

1double dblNum = 10.5; 2int num = (int)dblNum; //explicit type casting

In the above code, the double variable dblNum is being converted to an integer variable num using explicit type casting. Note the use of the cast operator (int) before the variable name.

Examples

Here are some examples to illustrate type casting in C#:

1//implicit type casting 2int num1 = 10; 3double dblNum1 = num1; 4 5//explicit type casting 6double dblNum2 = 10.5; 7int num2 = (int)dblNum2; 8 9//conversion of string to int 10string strNum = "10"; 11int num3 = int.Parse(strNum); 12 13//conversion of int to string 14int num4 = 20; 15string strNum2 = num4.ToString();

In the first example, an integer variable num1 is being implicitly type casted to a double variable dblNum1. In the second example, a double variable dblNum2 is being explicitly type casted to an integer variable num2.

The third example shows the conversion of a string variable strNum to an integer variable num3 using the int.Parse() method. The int.Parse() method converts the string to an integer data type.

The fourth example shows the conversion of an integer variable num4 to a string variable strNum2 using the ToString() method. The ToString() method converts the integer to a string data type.