Type casting is the process of converting one data type into another data type. Type casting can be explicit or implicit. The programmer does explicit type casting while the compiler does implicit type casting.
1. Implicit Casting
This type of casting occurs when you convert a smaller type to a larger type.
The order of implicit casting is char → int → long → float → double.
For example, consider the following code snippet:
intmyInt=10; doublemyDouble=myInt; // Automatic casting:- int to double Console.WriteLine(myInt); // Outputs 10 Console.WriteLine(myDouble); // Outputs 10
2. Explicit Casting
Explicit casting is done manually by placing the type in parentheses before the value.
It involves converting a larger type to a smaller size type, For instance:
doublemyDouble=123.99; intmyInt= (int)myDouble; // Manual casting:- double to int Console.WriteLine(myDouble); // Outputs- 123.99 Console.WriteLine(myInt); // Outputs- 123
C# Type Conversion Methods
You can also explicitly convert data types using built-in methods like Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (for int), and Convert.ToInt64 (for long), Example:
boolmyBool=false; intmyInt=12; doublemyDouble=7.75; Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int Console.WriteLine(Convert.ToString(myBool)); // Convert bool to string Console.WriteLine(Convert.ToString(myInt)); // Convert int to string Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double