Learn C# · lesson 12 of 61 · about 8 minutes
Conversions and Math
Read the hero's arrows without crashing: convert safely with TryParse, cast between number types, and keep HP at 0 or more with Math.Max.
What you'll learn
- Cast between int and double
- Convert safely with TryParse
- Use Math.Round, Max, Min, Abs, Pow and Sqrt
Counting arrows
Next the hero fires arrows, and the player types how many. If they type lots instead of a number, int.Parse would crash the whole battle. int.TryParse doesn't: it tries, and tells you whether it worked.
Safe conversion
int.Parse("12a") throws an exception. int.TryParse(text, out int n) doesn't: it returns true or false, and puts the number in n when it works.
Casts: (double)x widens an int; (int)3.99 chops to 3. Math.Round rounds, using banker's rounding by default (2.5 rounds to 2, 3.5 to 4).
Conversions and Math
int total = 7, count = 2;
Console.WriteLine($"{total / count} {(double)total / count}");
Console.WriteLine($"{(int)3.99} {Math.Round(3.5)} {Math.Round(2.5)}");
bool ok = int.TryParse("42", out int n);
bool bad = int.TryParse("12a", out int m);
Console.WriteLine($"{ok} {n} {bad} {m}");
Console.WriteLine($"{Math.Max(4, 9)} {Math.Abs(-7)} {Math.Pow(2, 3)} {Math.Sqrt(81)}");Output
3 3.5
3 4 2
True 42 False 0
9 7 8 9out and Math.Max
int.TryParse(text, out int arrows) creates arrows and fills it in: with the number when the text is a number, with 0 when it isn't. Math.Max(0, hp) picks the bigger of two numbers, so the HP shown never drops below 0.
Arrows
string text = "lots";
int.TryParse(text, out int arrows);
int left = Math.Max(0, 1 - arrows);
Console.WriteLine($"Arrows: {arrows}, Slime HP: {left}");
int.TryParse("2", out int more);
Console.WriteLine(Math.Max(0, 1 - more));Output
Arrows: 0, Slime HP: 1
0Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.