Skip to content
AgileLogics
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.Parse on untrusted input without a try/catch (or preferring int.TryParse, which reports success/failure instead of throwing) — covered fully in Exception Handling, Level 2.