Skip to main content

How to Read What the User Types with Console.ReadLine in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Console.ReadLine() waits for the user to type a line and press Enter, then gives back what they typed as a string. When there's nothing left to read, it gives back null instead, and ?. handles that in one step.

Console.Write and Console.WriteLine send text out to the terminal. Console.ReadLine brings text in. The .NET API reference: Reads the next line of characters from the standard input stream. When the user types at the keyboard, the ReadLine method blocks until the user presses the Enter key: the program stops at that line and waits.

What it returns, from the same reference: The next line of characters from the input stream, or null if no more lines are available. That's why its return type is string?, and not string: the ? says the result can be null, and the code that reads it has to be ready for that.

Syntax​

Syntax
string? <line> = Console.ReadLine();
string? <line> = Console.ReadLine()?.<Method>();
PartWhat it is
string?The type of what ReadLine returns: the text of the line, or null when the input has ended
<line>The variable that keeps what the user typed
Console.ReadLine()Waits until Enter is pressed, and returns the line without the Enter
?.<Method>()Optional. Calls a string method, such as Trim, only when the line isn't null

The C# fundamentals on ?.: The ?. operator accesses a member only when the object is non-null. When the object is null, the entire expression evaluates to null instead of throwing a NullReferenceException.

The Example​

A console app called ConsoleReadLine asks for the user's name, removes any spaces typed around it with Trim, and greets them with the number of letters in the name. It handles all three things the user can give it: a name, an empty line, and the end of the input.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ConsoleReadLine
cd ConsoleReadLine
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ConsoleReadLine/ConsoleReadLine.csproj:
Determining projects to restore...
Restored /Users/you/source/ConsoleReadLine/ConsoleReadLine.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n ConsoleReadLine creates a folder named ConsoleReadLine with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ConsoleReadLine.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, the question:

Program.cs (ask the question)
// Write, not WriteLine, so the answer is typed on the same line as the question.
Console.Write("What's your name? ");

Console.Write prints the question and leaves the cursor on the same line, so the user types the answer right after it. The space at the end keeps the answer from touching the question mark.

Then the answer:

Program.cs (read the answer)
// ReadLine waits until Enter is pressed and returns the line without the Enter.
// At the end of the input it returns null, and ?. then skips Trim and gives null too.
string? name = Console.ReadLine()?.Trim();

Console.ReadLine() waits for Enter and returns what was typed. ?.Trim() removes the spaces at the start and the end of it, but only when there's a line. When ReadLine returns null, ?. skips Trim, and name is null too.

Then one branch for each kind of answer:

Program.cs (handle each answer)
if (name is null)
{
Console.WriteLine();
Console.WriteLine("The input ended before a name was typed.");
}
else if (name == "")
{
Console.WriteLine("You pressed Enter without typing a name.");
}
else
{
Console.WriteLine($"Hello, {name}! Your name has {name.Length} letters.");
}

name is null is true when the input ended before a line was typed. The empty Console.WriteLine() moves to a new line first, because the cursor is still after the question. name == "" is true when Enter was pressed on an empty line. Otherwise, name.Length counts the characters in the name.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
What's your name? Maria
Hello, Maria! Your name has 5 letters.

macOS-style terminal window titled Terminal — ConsoleReadLine showing dotnet run printing What's your name? followed by Maria typed with spaces before it, then Hello, Maria! Your name has 5 letters.

The app stopped at the question and waited. Maria was typed with two spaces before the name and two after it, and then Enter. Trim removed the spaces, so the greeting reads Hello, Maria! and counts 5 letters, not 9.

The Complete File​

macOS-style code window titled Program.cs — ConsoleReadLine showing Console.Write asking What's your name?, Console.ReadLine with ?.Trim stored in a string? called name, and an if that handles a null name, an empty name and a name whose letters it counts

Program.cs
// Write, not WriteLine, so the answer is typed on the same line as the question.
Console.Write("What's your name? ");

// ReadLine waits until Enter is pressed and returns the line without the Enter.
// At the end of the input it returns null, and ?. then skips Trim and gives null too.
string? name = Console.ReadLine()?.Trim();

if (name is null)
{
Console.WriteLine();
Console.WriteLine("The input ended before a name was typed.");
}
else if (name == "")
{
Console.WriteLine("You pressed Enter without typing a name.");
}
else
{
Console.WriteLine($"Hello, {name}! Your name has {name.Length} letters.");
}

When the Input Ends​

ReadLine returns null when no more lines are available. At a terminal on macOS, pressing Ctrl+D at the question ends the input. Run again, with Ctrl+D pressed instead of a name, the app printed:

Output
What's your name?
The input ended before a name was typed.

ReadLine returned null, so ?. skipped Trim, name was null, and the first branch ran. The reference gives the keys for Windows: If the Ctrl+Z key combination (followed by Enter on Windows) is pressed when the method is reading input from the console, the method returns null. The runs in this post were on macOS, where Ctrl+D ended the input.

Common Mistakes​

MistakeWhat happensDo this instead
Storing the answer in a string and calling a method on it straight away, as in string name = Console.ReadLine(); and then name.Trim()The build warned warning CS8600: Converting null literal or possible null value to non-nullable type. and warning CS8602: Dereference of a possibly null reference. Run with nothing to read, it stopped with System.NullReferenceException: Object reference not set to an instance of an object.Declare string? and use ?., as in the example, and check for null before you use the name
Storing the answer straight in an int, as in int age = Console.ReadLine();error CS0029: Cannot implicitly convert type 'string' to 'int'. ReadLine always returns text, even when the user types digitsKeep the line in a string?, and turn it into a number in a separate step

FAQ​

Why Console.Write and not Console.WriteLine for the question?​

WriteLine ends the line after the question, so the answer goes on the next one. In a check that asked with Console.WriteLine("What's your name?"); and got Maria, the terminal showed:

Output
What's your name?
Maria
Hello, Maria!

Both work. Write keeps the question and the answer together on one line.

What does ReadLine return when Enter is pressed on an empty line?​

An empty string, "", and not null: the line is there, it just has nothing in it. The reference: The returned string does not contain the terminating character(s). Run with only Enter pressed, the app took the name == "" branch:

Output
What's your name?
You pressed Enter without typing a name.

Conclusion​

Console.ReadLine() waits for Enter and returns the line the user typed, without the Enter. Keep the result in a string?, because it's null when the input has ended, and use ?. to call methods such as Trim on it safely. Then handle each case: a null, an empty line, and a real answer.

Additional Resources​