Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Console.ReadLine() / Console.ReadKey()

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 / PropertyDescription
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.KeyReturns the pressed key as a ConsoleKey enum value.
ConsoleKeyInfo.KeyCharReturns 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 .