C#
Console.ReadKey
Learn to read a single key with Console.ReadKey.
A single key with Console.ReadKey
The Console.ReadKey() method reads a single key press from the user. It returns immediately when a key is pressed, without waiting for Enter. The return type is ConsoleKeyInfo, which carries several pieces of information about the key.
For example, ConsoleKeyInfo key = Console.ReadKey(); stores the pressed key in key. It is ideal for menu selection, press-any-key waits, or game-style applications.
Hidden key with ReadKey(true)
Calling Console.ReadKey(true) with the true argument prevents the pressed key from being displayed on the screen. This is called "intercept". It is useful for menu selections where you do not want the key to appear.
For example, ConsoleKeyInfo key = Console.ReadKey(true); reads the key but does not print it. The menu stays clean and only your own text appears. This is a common technique in interactive menus.
KeyChar and Key properties
The ConsoleKeyInfo struct has two commonly used properties: KeyChar gives the pressed character (char), while Key gives the ConsoleKey enum value of the key. You pick the one that matches whether you need the character or the key.
For example, key.KeyChar gives the character 'a', while key.Key gives ConsoleKey.A. Factors like Shift or Caps Lock affect KeyChar but Key stays the same.
Exercise Read a key and print its character
Read a key into key with Console.ReadKey(true). Then print "Key: " + key.KeyChar using Console.WriteLine.
Show example solution
Read the key with ConsoleKeyInfo key = Console.ReadKey(true); then print KeyChar with WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
ConsoleKeyInfo key = Console.ReadKey(true);
Console.WriteLine("Key: " + key.KeyChar);
}
}
Test yourself
-
What is the return type of Console.ReadKey()?
var key = Console.ReadKey();
- string
- ConsoleKeyInfo
- char
- int
Show answer
ConsoleKeyInfo — Correct! ReadKey returns a ConsoleKeyInfo struct.
-
Read the key silently
Console.WriteLine("Press any key to continue");
ConsoleKeyInfo key = ____;
Console.WriteLine(key.KeyChar);
Show answer
Console.WriteLine("Press any key to continue");
ConsoleKeyInfo key = Console.ReadKey(true);
Console.WriteLine(key.KeyChar);
-
Match each property with its description
- KeyChar
- Pressed character
- Key
- ConsoleKey enum value
- ReadKey(true)
- Suppresses the key on screen
Next lesson: int.Parse and TryParse