C# User Input

So far you have been sending text out to the screen with Console.WriteLine(). But a real program often needs to work the other way too, by reading what a person types on the keyboard. In C# this is done with Console.ReadLine(), which pauses the program, waits for the user to type something and press Enter, and then hands that text back to you as a string.

Reading text with Console.ReadLine()

The simplest way to collect input is Console.ReadLine(). It reads everything the user types until they press Enter, and returns it as a string. It is common to first print a short prompt so the user knows what to type, then store the result in a variable.

Ask for a name

Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + "!");

When you run this, the program stops at ReadLine() and waits. If you type Maria and press Enter, the output becomes "Hello Maria!". Whatever the user types is treated as plain text, even if they type numbers or symbols.

Note: Console.ReadLine() always gives you back a string. Even if the user types 42, you receive the text "42", not the number 42. To do math with it you must convert it first.

Reading numbers

Because input arrives as text, you convert it to a number before doing calculations. The Convert class is a beginner-friendly way to do this, with methods such as Convert.ToInt32() for whole numbers and Convert.ToDouble() for decimals.

Read a number and use it

Console.WriteLine("How old are you?");
int age = Convert.ToInt32(Console.ReadLine());
int nextYear = age + 1;
Console.WriteLine("Next year you will be " + nextYear);

Common conversion methods

MethodConverts input toExample result
Convert.ToInt32()int (whole number)"25" becomes 25
Convert.ToDouble()double (decimal)"3.5" becomes 3.5
Convert.ToBoolean()bool (true/false)"true" becomes true
Note: If the user types something that is not a valid number, such as "hello", a conversion like Convert.ToInt32() will throw an error and crash the program. Later, when you learn about exceptions and int.TryParse(), you will see safer ways to handle bad input.

Exercise: C# User Input

What type does Console.ReadLine() return?