C# Type Casting
Type casting means converting a value from one data type to another. C# supports implicit casting (automatic, safe conversions) and explicit casting (manual conversions that may lose data).
Implicit casting happens automatically when converting a smaller type to a larger one, like int to double. Explicit casting requires a cast operator and is needed when converting a larger type to a smaller one, like double to int.
(type)value;
Convert.ToInt32(value);
int.Parse(stringValue);Implicit casting
Implicit casting happens automatically when there's no risk of data loss, such as converting an int to a double. The compiler performs this conversion for you.
Explicit casting and Convert/Parse
Explicit casting uses parentheses, like `(int)myDouble`, and may lose data. The Convert class and Parse methods (like int.Parse) are used to convert strings to numbers and vice versa.
using System;
class Program {
static void Main() {
int myInt = 9;
double myDouble = myInt;
Console.WriteLine(myDouble);
}
}9int is implicitly converted to double since no data is lost.
using System;
class Program {
static void Main() {
double myDouble = 9.78;
int myInt = (int)myDouble;
Console.WriteLine(myInt);
}
}9Explicit casting truncates the decimal part when converting double to int.
Key points
- Implicit casting is automatic and safe (small type to large type).
- Explicit casting requires a cast operator and can lose data.
- Convert.ToInt32() and int.Parse() convert strings to numbers.
- ToString() converts a value into its string representation.
