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
int.TryParsereturns a bool and fills anoutvariable.out var ndeclares the target right at the call site.- The loop keeps the good values and names the bad input.
Keywords and builtins used here
elseforeachifinintnewoutvaluevar
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.
Step 3 of 3 in Methods, step 17 of 29 in Language basics.