8 minlesson

Reading User Input

Reading User Input

Interactive programs need to get input from users. This lesson shows you how to read and process user input in C# console applications.

Console.ReadLine()

The Console.ReadLine() method reads a line of text from the user:

csharp
1Console.Write("Enter your name: ");
2string name = Console.ReadLine();
3Console.WriteLine($"Hello, {name}!");

Write vs WriteLine for Prompts

csharp
1// WriteLine moves to next line (user types on new line)
2Console.WriteLine("Enter your name:");
3string name1 = Console.ReadLine();
4
5// Write stays on same line (user types after prompt)
6Console.Write("Enter your name: ");
7string name2 = Console.ReadLine(); // Better UX

Handling Null Input

ReadLine() can return null (when input stream ends). Handle it safely:

csharp
1// Using null-coalescing operator
2string input = Console.ReadLine() ?? "";
3
4// Using null-conditional
5string input = Console.ReadLine();
6if (input != null)
7{
8 // Process input
9}
10
11// Modern pattern
12string input = Console.ReadLine() ?? string.Empty;

Converting Input to Numbers

User input is always a string. Convert it to use as numbers:

Using Parse (simple but throws exceptions)

csharp
1Console.Write("Enter your age: ");
2string input = Console.ReadLine() ?? "";
3int age = int.Parse(input);
4Console.WriteLine($"Next year you'll be {age + 1}");

Using TryParse (safe, recommended)

csharp
1Console.Write("Enter your age: ");
2string input = Console.ReadLine() ?? "";
3
4if (int.TryParse(input, out int age))
5{
6 Console.WriteLine($"Next year you'll be {age + 1}");
7}
8else
9{
10 Console.WriteLine("Invalid number!");
11}

Converting Different Types

csharp
1Console.Write("Enter a whole number: ");
2int wholeNumber = int.Parse(Console.ReadLine() ?? "0");
3
4Console.Write("Enter a decimal number: ");
5double decimalNumber = double.Parse(Console.ReadLine() ?? "0");
6
7Console.Write("Enter a price: ");
8decimal price = decimal.Parse(Console.ReadLine() ?? "0");
9
10Console.Write("True or false? ");
11bool answer = bool.Parse(Console.ReadLine() ?? "false");

Complete Input Pattern

Here's a robust pattern for reading numeric input:

csharp
1int GetIntFromUser(string prompt)
2{
3 while (true)
4 {
5 Console.Write(prompt);
6 string input = Console.ReadLine() ?? "";
7
8 if (int.TryParse(input, out int result))
9 {
10 return result;
11 }
12
13 Console.WriteLine("Invalid number. Please try again.");
14 }
15}
16
17// Usage
18int age = GetIntFromUser("Enter your age: ");
19Console.WriteLine($"You are {age} years old.");

Reading Single Characters

For single character input, you can use:

csharp
1// Read a line and take first character
2Console.Write("Enter a letter: ");
3string input = Console.ReadLine() ?? "";
4if (input.Length > 0)
5{
6 char letter = input[0];
7 Console.WriteLine($"You entered: {letter}");
8}
9
10// Or use Console.ReadKey for immediate input
11Console.Write("Press any key: ");
12ConsoleKeyInfo keyInfo = Console.ReadKey();
13char key = keyInfo.KeyChar;
14Console.WriteLine($"\nYou pressed: {key}");

Console.ReadKey()

For immediate character input without pressing Enter:

csharp
1Console.Write("Press Y or N: ");
2ConsoleKeyInfo key = Console.ReadKey();
3Console.WriteLine(); // Move to next line
4
5if (key.Key == ConsoleKey.Y)
6{
7 Console.WriteLine("You chose Yes");
8}
9else if (key.Key == ConsoleKey.N)
10{
11 Console.WriteLine("You chose No");
12}

Practical Examples

Simple Calculator Input

csharp
1Console.Write("Enter first number: ");
2if (!double.TryParse(Console.ReadLine(), out double num1))
3{
4 Console.WriteLine("Invalid number!");
5 return;
6}
7
8Console.Write("Enter second number: ");
9if (!double.TryParse(Console.ReadLine(), out double num2))
10{
11 Console.WriteLine("Invalid number!");
12 return;
13}
14
15Console.WriteLine($"Sum: {num1 + num2}");
16Console.WriteLine($"Difference: {num1 - num2}");
17Console.WriteLine($"Product: {num1 * num2}");
18if (num2 != 0)
19{
20 Console.WriteLine($"Quotient: {num1 / num2}");
21}

Menu Selection

csharp
1Console.WriteLine("=== Main Menu ===");
2Console.WriteLine("1. Start Game");
3Console.WriteLine("2. Settings");
4Console.WriteLine("3. Exit");
5Console.Write("Choose an option: ");
6
7string choice = Console.ReadLine() ?? "";
8
9switch (choice)
10{
11 case "1":
12 Console.WriteLine("Starting game...");
13 break;
14 case "2":
15 Console.WriteLine("Opening settings...");
16 break;
17 case "3":
18 Console.WriteLine("Goodbye!");
19 break;
20 default:
21 Console.WriteLine("Invalid option!");
22 break;
23}

Yes/No Confirmation

csharp
1Console.Write("Are you sure? (yes/no): ");
2string response = Console.ReadLine()?.ToLower() ?? "";
3
4if (response == "yes" || response == "y")
5{
6 Console.WriteLine("Confirmed!");
7}
8else
9{
10 Console.WriteLine("Cancelled.");
11}

Summary

In this lesson, you learned:

  • Console.ReadLine() reads a line of text from the user
  • Use Console.Write() for prompts to keep cursor on same line
  • Always handle potential null input with ?? operator
  • Convert strings to numbers with Parse() or TryParse()
  • Use Console.ReadKey() for immediate single-key input
  • Validate user input before using it

Now you're ready for the hands-on calculator workshop!