User Input, Console.ReadLine() & Validation Masterclass
Welcome to Phase 3 (Chapter 8): C# User Input, Console.ReadLine(), Parsing & Input Validation Masterclass! Capturing input from the console terminal is essential for building interactive software. In this lesson, we explore reading strings via Console.ReadLine(), parsing integers, decimals, and characters, handling null/empty inputs, building fail-safe validation loops with int.TryParse(), and constructing interactive CLI menu loops.
The Console.ReadLine() method pauses execution and waits for the user to type text into the terminal window and press Enter. It returns the entered text as a nullable string (string?).
Console.Write("Enter your name: ");
string? name = Console.ReadLine();
Console.WriteLine($"Hello, {name}! Welcome to C# Masterclass.");
Because Console.ReadLine() always returns a string, converting it to numbers requires parsing. Using int.Parse() directly on invalid user input throws a FormatException. The int.TryParse() pattern is the industry standard for safe parsing without exceptions:
Console.Write("Enter your age: ");
string? ageInput = Console.ReadLine();
// int.TryParse returns true if successful and populates the out variable 'age'
if (int.TryParse(ageInput, out int age))
{
Console.WriteLine($"Valid Age: {age}");
}
else
{
Console.WriteLine("Invalid age entered! Please enter a valid integer.");
}
// Reading Decimals (Salary / Price)
Console.Write("Enter salary: ");
if (decimal.TryParse(Console.ReadLine(), out decimal salary))
{
Console.WriteLine($"Entered Salary: {salary:C}");
}
// Reading Characters (Grade / Choice)
Console.Write("Enter grade (A, B, C): ");
if (char.TryParse(Console.ReadLine(), out char grade))
{
Console.WriteLine($"Grade Character: {grade}");
}
To prevent users from entering blank strings or invalid data, wrap Console.ReadLine() in a validation loop:
string? username;
// Prompt repeatedly until user provides a non-empty name
do
{
Console.Write("Enter a valid non-empty username: ");
username = Console.ReadLine();
} while (string.IsNullOrWhiteSpace(username));
Console.WriteLine($"Username set to: '{username.Trim()}'");
// Number validation loop
int validAge;
Console.Write("Enter your age (1-120): ");
while (!int.TryParse(Console.ReadLine(), out validAge) || validAge < 1 || validAge > 120)
{
Console.Write("Invalid age! Please enter a number between 1 and 120: ");
}
Console.WriteLine($"Confirmed Age: {validAge}");
bool running = true;
while (running)
{
Console.WriteLine("
=== C# CONSOLE APPLICATION MENU ===");
Console.WriteLine("1. Greet User");
Console.WriteLine("2. Calculate Square of a Number");
Console.WriteLine("3. Exit Application");
Console.Write("Select an option (1-3): ");
string? option = Console.ReadLine();
switch (option)
{
case "1":
Console.WriteLine("Hello! Hope you are enjoying C#!");
break;
case "2":
Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int n))
Console.WriteLine($"Square of {n} is {n * n}");
else
Console.WriteLine("Invalid number!");
break;
case "3":
running = false;
Console.WriteLine("Exiting menu... Goodbye!");
break;
default:
Console.WriteLine("Invalid choice! Please select 1, 2, or 3.");
break;
}
}
Q1: Why does Console.ReadLine() return string? nullable?
Because the input stream could reach EOF (End of File) or be cancelled, Console.ReadLine() returns string? (nullable string). Always handle potential null or empty values.
Q2: How do I read a single keypress without requiring the user to press Enter?
Use Console.ReadKey(). For example: ConsoleKeyInfo key = Console.ReadKey(intercept: true);.