C#
Console.ReadLine
Learn to read a line from the user with Console.ReadLine.
Reading a line with Console.ReadLine
The Console.ReadLine() method reads one line from the console. It waits until the user presses Enter and returns the typed characters as a string. The return type is string, so you assign the result to a string variable.
For example, string name = Console.ReadLine(); stores the name the user typed in the name variable. When you expect a number, you need an extra conversion step; we will cover that in later lessons.
Storing the input
To use the input later, you must assign it to a variable. You can put the result of Console.ReadLine() directly into a string variable, then print it back with Console.WriteLine.
A common flow: first print a cue with Console.Write("Name: ");, then read the input with string name = Console.ReadLine();. This way the user knows what to type and you keep the input in a variable.
Null at the end of input
Console.ReadLine() returns null when the input stream ends (for example, when redirected input from a file is exhausted). It is good practice to check for null before using the result.
For example, after string line = Console.ReadLine(); you can guard with if (line != null) { ... } so the program does not crash unexpectedly. In an interactive console null is rare, but it is still worth handling.
Exercise Read the name and greet
Read a line with Console.ReadLine() and store it in name. Then print "Hello, " + name + "!" using Console.WriteLine.
Show example solution
Read the input with string name = Console.ReadLine(); then print the greeting with Console.WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
}
}
Test yourself
-
What is the return type of Console.ReadLine()?
string s = Console.ReadLine();
Show answer
string — Correct! ReadLine reads a line and returns a string.
-
Read the name
Console.Write("Name: ");
string name = ____;
Console.WriteLine(name);
Show answer
Console.Write("Name: ");
string name = Console.ReadLine();
Console.WriteLine(name);
-
Match each method to its job
- Console.ReadLine()
- Reads a full line
- Console.Read()
- Reads a character code
- Console.ReadKey()
- Reads a single key press
Next lesson: Console.ReadKey