Validation and TryParse
Validation and TryParse
Validation checks whether an input is acceptable before the program uses it. Parsing converts a text representation to a typed value. int.TryParse returns a Boolean indicating whether the conversion succeeded and writes the result through an out parameter. A successful parse does not mean the value meets the rules of your application.
using System;using System.Globalization;foreach (string text in new[] { "0", "abc", "12" }){ bool ok = int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out int value); Console.WriteLine($"{text}: {ok}, {value}");}Both zero and abc produce a zero output value, but only zero is a successful conversion. All examples use fixed invariant formatting assumptions.
Expected output (reasoned, not executed):
0: True, 0abc: False, 012: True, 12Check conversion before using the value
int.TryParse(text, out int quantity) accepts common integer text according to its default parsing rules and current culture. If conversion fails, the result of this overload is zero. Zero may also be a valid successful result, so always check the Boolean. The explicit overload with NumberStyles and CultureInfo makes the intended format clear. NumberStyles.None excludes signs, whitespace and grouping separators under ordinary integer input; use NumberStyles.Integer when signed numbers and leading/trailing whitespace are permitted. For exact protocol grammars, validate permitted characters independently: parsing is not a complete lexical allowlist.
Add a business rule after parsing
For a shelf quantity, choose a domain such as 1 through 100 inclusive. Parse the text first, then reject converted numbers outside the domain. Use a specific message for each failure. When input may be null, handle it without dereferencing it. TryParse accepts null text as failure for the shown string overload. Keep the validation function free of unrelated mutations so it is easy to test. Prefer invariant culture for machine-readable numeric formats; use a deliberately selected culture for user-facing localized values.
using System;using System.Globalization;foreach (string text in new[] { "1", "100", "101", "0", "abc" }) Console.WriteLine(text + ": " + CheckQuantity(text));static string CheckQuantity(string text){ if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out int quantity)) return "Invalid integer"; if (quantity < 1 || quantity > 100) return "Out of range"; return "Accepted";}Parsing and range validation are independent. Both endpoints are included, and invalid input cannot reach the accepted branch.
Expected output (reasoned, not executed):
1: Accepted100: Accepted101: Out of range0: Out of rangeabc: Invalid integerusing System;using System.Globalization;string?[] inputs = { null, " 7 ", "+7", "7", "2147483648" };foreach (string? input in inputs){ bool strict = int.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out _); bool signed = int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out _); Console.WriteLine((input ?? "null") + ": " + strict + "/" + signed);}The two styles differ in whitespace and sign handling. Null and the value larger than Int32.MaxValue fail in both. The underscore is a discard: the program uses only the Boolean result.
Expected output (reasoned, not executed):
null: False/False 7 : False/True+7: False/True7: True/True2147483648: False/FalseCommon mistakes
Checking quantity == 0 after TryParse loses the distinction between invalid input and a valid zero. Do not use a successful parse as proof of authorization or all business rules. Keep lexical policy, numeric range, domain checks and authorization separate.
Practice
Write a validation method for a seating count between 1 and 8 inclusive. Allow only the ordinary unsigned integer format used by NumberStyles.None; use invariant culture. Return distinct messages for parse failure, range failure and success. Test null, empty text, 0, 1, 8, 9, -1, 2.5 and 2147483648.
Predict the outcome before checking your work. The separate manual practice and quiz are staged, not automatically graded.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Validation and TryParse — knowledge check
Apply the lesson concepts to the following scenarios.
What distinguishes a successful parse of 0 from failed conversion?
Does successfully parsing 101 make it a valid quantity for 1–100?
Which style allows leading sign and surrounding whitespace in the example?
What happens when parsing 2147483648 as int?
Why select invariant culture for machine-readable values?