Skip to content
Justice Tech School

C# Type Casting

Widening conversions are automatic, narrowing needs a cast. Convert and Parse change text to numbers. TryParse is safe because it does not throw.

Example
int i = 9;
double d = i;
int back = (int)9.78;
int n = Convert.ToInt32("42");
bool ok = int.TryParse("abc", out int x);
Console.WriteLine($"{d} {back} {n} {ok}");

Exercise

Convert text to int safely.

int.("12", out int n)

Quiz Test

Which is safest for user text?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.