C#
Public
Read Console Input Safely
Read a number from the console without crashing on invalid input.
#csharp
#console
#input
#beginner
C#
using System;
Console.Write("Enter your age: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age))
{
Console.WriteLine($"You are {age} years old.");
}
else
{
Console.WriteLine("Please enter a valid number.");
}
Notes
TryParse is safer than Parse because invalid input does not throw an exception.