Lesson 16: Safe input (int.TryParse)
int.Parse is great — but if the user types text that isn't a number (like "abc"), it crashes. int.TryParse is safer: int.TryParse(text, out int n) tries to convert, returns true if it worked (and the number goes into n), or false if it failed. So you can check with if before using the value.
TryParse is like trying a key in a lock: it tells you 'did it work?' (true/false). If yes — the number is waiting in n. If not — no crash, you just handle it.
- int.TryParse()
- Tries to convert text to a number; returns true/false on success, without crashing.
- out int n
- An output parameter: if the conversion succeeded, the number goes into the variable n.
- Parse crashes
- int.Parse("abc") throws an error; TryParse returns false instead.