Console.ReadLine() / Console.ReadKey()
Console.ReadLine() reads a line of text from the console, and Console.ReadKey() reads a single key press.
Syntax
// Reads a line of text input (confirmed with the Enter key). string line = Console.ReadLine(); // Waits for a single key press and reads it. ConsoleKeyInfo key = Console.ReadKey(); ConsoleKeyInfo key = Console.ReadKey(bool intercept); // Pass true to suppress display on screen
Method List
| Method / Property | Description |
|---|---|
| Console.ReadLine() | Returns a single line up to the Enter key as a string. Returns null if the end of the stream is reached. |
| Console.ReadKey() | Returns the next key press as a ConsoleKeyInfo value. The pressed character is echoed to the console. |
| Console.ReadKey(true) | Reads a key press but suppresses echo to the console. Useful for password input. |
| ConsoleKeyInfo.Key | Returns the pressed key as a ConsoleKey enum value. |
| ConsoleKeyInfo.KeyChar | Returns the character (char) of the pressed key. |
Sample Code
using System;
// Read a string with ReadLine().
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
// To use the input as a number, you need to convert it.
Console.Write("Enter your age: ");
string input = Console.ReadLine();
if (int.TryParse(input, out int age)) {
Console.WriteLine($"Next year you will be {age + 1}.");
} else {
Console.WriteLine("Please enter a number.");
}
// Use ReadKey() to wait for any key press.
Console.WriteLine("Press any key...");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine(); // ReadKey does not add a newline, so we add one manually.
Console.WriteLine($"Key pressed: {keyInfo.Key}");
Console.WriteLine($"Character: {keyInfo.KeyChar}");
// Branch logic based on a specific key.
Console.WriteLine("Select Y/N: ");
ConsoleKeyInfo choice = Console.ReadKey(true); // Does not display the pressed character on screen.
if (choice.Key == ConsoleKey.Y) {
Console.WriteLine("You selected Yes.");
} else {
Console.WriteLine("You selected No.");
}
Notes
Because Console.ReadLine() returns a string, you need to convert it using int.Parse() or int.TryParse() if you want to use it as a number. Always validate user input.
Console.ReadKey() is well suited for UIs that respond immediately to a single key press, such as pausing a program ("Press any key to continue") or navigating a menu. Passing true to intercept suppresses the echoed character, making it useful for implementing password input.
For writing output to the console, see Console.WriteLine() / Console.Write().
If you find any errors or copyright issues, please contact us.