C# Type Casting
Type casting in C# allows you to convert a variable from one data type to another. There are two main types of type casting:
Key Topics
1. Implicit Casting
Implicit casting happens automatically when converting a smaller type to a larger type. For example, int to double. This is safe and does not cause data loss.
Example
// Implicit casting from int to double
int myInt = 10;
double myDouble = myInt; // Implicit casting
Console.WriteLine(myInt); // Outputs 10
Console.WriteLine(myDouble); // Outputs 10.0
Output:
Explanation: In this example, the integer myInt is automatically converted to a double. The conversion is implicit and safe because a double can hold both integer and decimal values.
2. Explicit Casting
Explicit casting must be done manually because data loss can occur. For example, when converting a double to an int, the fractional part is lost.
Example
// Explicit casting from double to int
double myDouble = 9.78;
int myInt = (int)myDouble; // Explicit casting
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
Output:
Explanation: The double value 9.78 is explicitly cast to an int. The fractional part is lost, and only the integer portion remains.
3. Converting String to Number Types
You can convert a string to a number using methods like Convert.ToInt32() or int.Parse(). To safely handle invalid input, you can use int.TryParse() to prevent exceptions.
Example
string input = "123";
int result;
if (int.TryParse(input, out result)) {
Console.WriteLine("Parsed value: " + result);
} else {
Console.WriteLine("Invalid input");
}
Output:
Explanation: The TryParse() method tries to convert the input string into an integer. If it succeeds, it prints the parsed value; if not, it prints Invalid input.
4. Boxing and Unboxing
Boxing is the process of converting a value type (e.g., int) into an object type. Unboxing is the reverse process, converting the object back to a value type.
Example
int myInt = 123; // Value type
object myObj = myInt; // Boxing
int unboxedInt = (int)myObj; // Unboxing
Console.WriteLine(myObj); // Outputs 123
Console.WriteLine(unboxedInt); // Outputs 123
Output:
Explanation: The integer myInt is boxed into the object myObj and then unboxed back into an integer unboxedInt. Both values remain the same throughout the process.