C# – Waiting for user input in a Console App

The following code shows how to wait for user input in a Console App:

static void Main(string[] args) { while (true) { Console.Write("Type something: "); var input = Console.ReadLine(); //Process input Console.WriteLine(input); } }
Code language: C# (cs)

When the user types something in and presses the Enter key, Console.ReadLine() will return what they typed.

Type something: hello hello Type something:
Code language: plaintext (plaintext)

Console.ReadLine() vs Console.ReadKey()

Console.ReadLine() waits for the user to press Enter, and then returns everything they typed in.

Console.ReadKey() returns individual key presses. It returns a ConsoleKeyInfo object, which allows you to examine which key they pressed (including if it was a key press combo like Ctrl-A).

Here’s an example of using Console.ReadKey(). Let’s say when the user presses a key, you want to uppercase it, and show them the uppercased version. Here’s how you’d do that:

static void Main(string[] args) { while (true) { Console.Write("Type something: "); ConsoleKeyInfo keyPress = Console.ReadKey(intercept: true); while (keyPress.Key != ConsoleKey.Enter) { Console.Write(keyPress.KeyChar.ToString().ToUpper()); keyPress = Console.ReadKey(intercept: true); } Console.WriteLine(); } }
Code language: C# (cs)

When I run this and type “hello”, it intercepts each letter I typed in and outputs the uppercased version. This is what the output looks like:

Type something: HELLO Type something:
Code language: plaintext (plaintext)

Leave a Comment