Validate Input with TryParse
TryParse is a foundational C# pattern for converting untrusted text.
How it works
Parse user input without using exceptions for ordinary validation.
TryParse returns false and assigns the type's default value when conversion fails.
Runnable C# example
Program.cs
using System;
class Program
{
static void Main()
{
foreach (string input in new[] { "42", "oops" })
Console.WriteLine(int.TryParse(input, out int value) ? value * 2 : "Invalid");
}
}
84
InvalidPractice with the debugger
Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.