typestar

TryParse & out in C#

Parsing that reports failure instead of throwing.

// TryParse reports success and hands the value out through a parameter
if (int.TryParse("128", out var value))
{
    Console.WriteLine($"parsed {value}");
}

var inputs = new[] { "3", "x", "77" };
var sum = 0;
foreach (var text in inputs)
{
    if (int.TryParse(text, out var n)) sum += n;
    else Console.WriteLine($"skipping '{text}'");
}
Console.WriteLine($"sum {sum}");

How it works

  1. int.TryParse returns a bool and fills an out variable.
  2. out var n declares the target right at the call site.
  3. The loop keeps the good values and names the bad input.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
363
Tokens
83
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 3 of 3 in Methods, step 17 of 29 in Language basics.

← Previous Next →