C# and .NET • Modern C# baseline
Parse and Validate User Input
Prefer TryParse for expected invalid input and validate business rules separately.
Parsing answers whether text can be represented as a type; it does not tell you whether the value makes sense for the application. TryParse reports failure without using exceptions for routine bad input. After parsing, apply range, authorization, and business-rule checks.
Key points
- Use a suitable culture when parsing user-facing numbers.
- Treat input validation and authorization as separate responsibilities.
Example
Console.Write("Age: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age) && age >= 0 && age <= 130)
{
Console.WriteLine($"Accepted: {age}");
}
else
{
Console.WriteLine("Enter a whole number from 0 to 130.");
}
What to expect
A valid age from 0 through 130 is accepted; malformed and out-of-range values are rejected.
Practice exercise
Add a second validation rule for a registration form and decide which error should be shown first.
Key idea: Separate conversion success from domain validity.