2 · Model and validate · 25 MIN
TryParse and expected failures
Invalid input can be an ordinary result instead of an exception.
TryParse returns a boolean and an out value. Use the value only when parsing succeeds, then apply business limits. This is useful when malformed user input is expected frequently. Exceptions still belong to unexpected or explicitly exceptional paths; do not catch every exception and claim success. Culture influences numeric formats, so this exercise fixes invariant integer parsing rather than inheriting the host machine’s locale. Separate this conversion from any database update so rejected values cannot mutate stored state.
First validate representation, then validate domain range.
Read the example
using System;
using System.Globalization;
foreach (var raw in new[]{"3","-1","many"}) {
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n))
Console.WriteLine("invalid integer");
else if (n < 0) Console.WriteLine("negative");
else Console.WriteLine(n);
}Check the expected output
3 negative invalid integer
Your challenge
Extract a reusable validation function with a maximum of 1000 and an explicit error message result.
Solution cost: O(m) parsing for m characters. time · Account for collection storage separately from the returned result. space
Common trap
Reading an out value after TryParse returned false treats invalid data as a real zero.
Study the project implementation
using System;
using System.Globalization;
foreach (var raw in new[]{"3","-1","many"}) {
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n))
Console.WriteLine("invalid integer");
else if (n < 0) Console.WriteLine("negative");
else Console.WriteLine(n);
}Further reading: Official documentation
Next lesson: Async, await and cancellation →