User Input, Console.ReadLine() & Validation Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 8 of 35 ๐Ÿ“‚ Phase 3: Operators & User Input ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Console.ReadLine() ยท Reading Numbers & Chars ยท int.TryParse() Validation ยท Handling Empty Input ยท Menu-Driven Input Loop ยท Console.ReadKey()

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.

1Console.ReadLine() & String Input

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?).

C# โ€” Basic User Input โ–ถ Run in Compiler
Console.Write("Enter your name: ");
string? name = Console.ReadLine();

Console.WriteLine($"Hello, {name}! Welcome to C# Masterclass.");
2Reading & Parsing Numbers (TryParse Pattern)

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:

C# โ€” Safe Input Validation with TryParse โ–ถ Run in Compiler
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}");
}
3Handling Empty Input & Input Validation Loop

To prevent users from entering blank strings or invalid data, wrap Console.ReadLine() in a validation loop:

C# โ€” Fail-Safe Input Validation Loop โ–ถ Run in Compiler
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}");
4Building an Interactive Menu Input System
C# โ€” Interactive Menu System โ–ถ Run in Compiler
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;
    }
}
5Technical FAQs

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);.