Validate Input with TryParse
Parse user input without using exceptions for ordinary validation.
Introduction
TryParse is a foundational C# pattern for converting untrusted text.
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.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges