Charlie Calvert on Elvenware

Writing Code and Prose on Computers

Elvenware

Console ReadKey

Use Console.ReadKey when you want to get a single character of input from the user. For instance, if you are trying to detect if the user entered the RightArrow key, or if you want to get input for a quiz, such as T for True or F for False. If you want to get someone's name, or a number with multiple digits, then you should use ReadLine or Read.

Remember that ReadKey returns a type called ConsoleKeyInfo, which is a class that has multiple fields:

class = ConsoleKeyInfo
{
  public ConsoleKey Key { get; }
  public char KeyChar { get; }
  // Code omitted here...
}

You need to understand Key and KeyChar. In particular, focus on KeyChar. This is the char, or character, that the user pressed during the call to ReadKey. For instance, if the user pressed the A key, then KeyChar will hold the char 'a'. If they pressed Shift + A, then it KeyChar will hold the char 'A'. 

Here is an example of how to use ReadKey:

Console.WriteLine("Enter 1, 2 or 3");
ConsoleKeyInfo input = Console.ReadKey();
switch (input.KeyChar)
{
    case '1':
        Console.WriteLine("Great, you earned on point");
        break;

    case '2':
        Console.WriteLine("You earned two points");
        break;

    case '3':
        Console.WriteLine("You earned three points");
        break;

    default:
        Console.WriteLine("Sorry, you didn't win anything");
        break;
}

Now here is an example that uses ReadLine, instead of ReadKey:

Console.WriteLine("Enter the string one two or three");
string input = Console.ReadLine();
switch (input)
{
    case "one":
        Console.WriteLine("Great, you earned on point");
        break;

    case "two":
        Console.WriteLine("You earned two points");
        break;

    case "three":
        Console.WriteLine("You earned three points");
        break;

    default:
        Console.WriteLine("Sorry, you didn't win anything");
        break;
}

Here is an example of using ReadKey to get input from the NumPad:

Console.Write("Enter an numpad 1: ");
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine();
if (input.Key == ConsoleKey.NumPad1)
    Console.WriteLine("The user entered NumPad1");
else
    Console.WriteLine("The user entered some other key");

Watch the video on YouTube