4 min read
Type Casting & Conversion
Prerequisites: Variables & data types
int whole = 42;
double asDouble = whole; // widening: automatic, safe
double price = 19.99;
int asInt = (int) price; // narrowing: explicit cast required
Console.WriteLine(asInt); // 19 — truncated, not rounded
string text = "42";
int parsed = int.Parse(text); // throws if invalid
bool ok = int.TryParse(text, out int n); // safer — no exception
Common mistakes
- Using
int.Parseon untrusted input without atry/catch(or preferringint.TryParse, which reports success/failure instead of throwing) — covered fully in Exception Handling, Level 2.