Loading lessons...
Type Casting
C# Type Casting
Type casting is converting a value from one data type to another.
Two ways to convert
- Implicit - automatic, happens when converting a smaller type to a larger one (no data loss).
- Explicit - manual, needed when converting a larger type to a smaller one (possible data loss).
Implicit casting (automatic)
The compiler converts automatically from smaller to larger types:
int myInt = 9;
double myDouble = myInt; // Automatic: int -> double
Implicit conversions: char -> int -> long -> float -> double.
Explicit casting (manual)
Use parentheses with the target type. This is required when going from a larger type to a smaller one:
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual: double -> int
myInt becomes 9 - the decimal part is truncated (not rounded).
Conversion Methods
The .NET Convert class handles conversions between types:
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // "10"
Console.WriteLine(Convert.ToDouble(myInt)); // 10
Console.WriteLine(Convert.ToInt32(myDouble)); // 5
Console.WriteLine(Convert.ToString(myBool)); // "True"
Parsing strings
Convert a string into a number with int.Parse or Convert.ToInt32:
string text = "42";
int number = int.Parse(text);
TL;DR
- Implicit casting is automatic (small -> large).
- Explicit casting uses
(type)and may lose data. Convert.ToString,Convert.ToInt32, etc. convert between types.- Use
int.Parseto turn a string into a number.