C# Foundations · Lesson 26

The Try pattern and out results

Separate successful parsing from the value produced by a parser.

How it works

A Try method reports success with a bool and returns its useful result through an out parameter. This pattern fits operations where invalid input is expected during normal use, such as reading a number from a form. The result variable must be interpreted together with the success flag. The variable's value alone cannot prove that parsing succeeded.

An out argument may be declared directly at the call site. C# ensures that the called method assigns an out parameter before returning normally. That definite-assignment rule is a language guarantee, but the semantic meaning of a failure value still belongs to the method contract. In particular, a legitimate zero and a parsing failure can both leave the numeric result equal to zero.

Walk through the example. The loop tries three strings using invariant integer parsing. The valid positive number and the valid zero both reach the success branch. The word zero reaches the failure branch, which prints an explicit rejection message rather than using the out value. A separate TryDouble method demonstrates the same shape for a small domain calculation.

Watch the boundary. Do not ignore the boolean and continue with the out value. That turns malformed input into a plausible number and can quietly alter totals. A successful parse also proves only a syntactic conversion, not a business rule. For example, a parsed negative age may still be invalid. Apply domain validation after conversion and report those failures distinctly.

Practice independently. Write TryReadPercentage that accepts text, parses an integer using an explicit culture, and succeeds only for values from zero through one hundred. Test malformed text, both valid boundaries, and values just outside the range. Decide what result value the function writes on failure and keep callers dependent on the success flag. Explain why parsing and range validation are separate checks.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

foreach (string text in new[] { "12", "0", "zero" })
{
    if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value))
        Console.WriteLine($"accepted:{value}");
    else
        Console.WriteLine("rejected");
}
bool TryDouble(int value, out int doubled)
{
    doubled = value * 2;
    return value >= 0;
}
Console.WriteLine(TryDouble(4, out int result));
Console.WriteLine(result);

Expected output

accepted:12
accepted:0
rejected
True
8
Try this
Use the success flag before consuming the out result, then validate domain rules.