CodShot
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.

Snippet actions

CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support