Practical .NET · Lesson 2

Validation

TryParse checks input without throwing.

How it works

decimal.TryParse returns false instead of throwing, and puts the value in an out variable when it succeeds. That makes it the right tool for user input, where bad text is normal. The guard clause rejects negative amounts before they reach the total. Only 12.50 and 4 pass both checks, so the total is 16.50.

A working example

var inputs = new[] { "12.50", "abc", "-3", "4" };
var total = 0m;

foreach (var text in inputs)
{
    if (!decimal.TryParse(text, System.Globalization.CultureInfo.InvariantCulture, out var amount))
    {
        Console.WriteLine($"skip {text}: not a number");
        continue;
    }
    if (amount < 0)
    {
        Console.WriteLine($"skip {text}: negative");
        continue;
    }
    total += amount;
}

Console.WriteLine($"total {total}");

Expected output

skip abc: not a number
skip -3: negative
total 16.50
Try this
TryParse answers yes or no. The value comes back through out.