Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 182 ยท Getting Started

Reading Input

Learn how C# programs read input - Console.ReadLine and null at end of input, parsing with int.Parse and TryParse, validation loops and reading all lines at once.

A program that only prints is a poster; a program that reads input is a conversation. Whether the text comes from a person typing, a file redirected into the program or another program's output, the console reads it the same way: one line at a time, as text. Turning that text into numbers, and surviving input that is wrong, is most of the work.

In this lesson you will use Console.ReadLine, learn why it can return null, convert text to numbers safely with TryParse, build a validation loop and read an entire input stream at once. Every example here has its input preset in the Input box under the editor, so you can run it right away and then change the input to see how the program reacts.

In a real terminal, Console.ReadLine() waits until the user presses Enter. In our editor there is no keyboard: the lines in the Input box are fed to the program in order, and when they run out, the program sees end of input. That is the same thing that happens when you run dotnet run < data.txt on your machine.

Console.ReadLine

Console.ReadLine() reads characters up to the next line break, removes the line break and returns the text as a string.

C# Reading a name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the type string?. The question mark means "this may be null", and the compiler insists on it because ReadLine returns null when there is nothing left to read. We will see exactly when that happens in a moment. The expression name?.Length is the null-conditional operator: it gives the length when name is not null, and null otherwise (see Null-Handling Operators).

Why Write for the question and WriteLine for the answer? Console.Write does not add a line break, so the cursor stays on the same line, and the user types right after the prompt. Output is covered in Console Output and Formatting.

Everything is text

Whatever the user types, ReadLine gives you a string. If they type 42, you receive the two characters '4' and '2', not the number. Adding two such strings glues them together:

C# Strings are not numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first line prints 2022, the second 42. To do arithmetic you must parse the text. The ! after first is the null-forgiving operator: it tells the compiler "I know this is not null here". Use it sparingly, only when you truly know; we will replace it with a safer pattern soon.

Parse and TryParse

Every numeric type has two ways to convert text:

  • int.Parse(text) returns the number, or throws an exception (FormatException for bad text, OverflowException if the number is too big, ArgumentNullException for null).
  • int.TryParse(text, out int result) returns true or false and never throws for bad text. When it returns true, result holds the number; otherwise result is 0.

Use Parse when bad input is a bug (for instance, data your own program wrote). Use TryParse when bad input is normal, which is everything a human types.

C# TryParse for human input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at the results: 12 and -3 parse. abc and 7.5 fail (an int cannot hold a fraction). " 8 " succeeds, because the number styles that TryParse uses by default allow leading and trailing spaces. 99999999999 is too large for an int (maximum 2,147,483,647), and TryParse reports that as a plain false, not an exception. If you need larger values, use long.TryParse; there is a lesson on integer types.

The out int number syntax declares the variable right inside the call. This is an out variable, explained fully in Parameters.

Other types work the same way: double.TryParse, decimal.TryParse, bool.TryParse (accepts True/false, ignoring case), DateTime.TryParse, and so on. Number parsing depends on the culture, because some countries write 3,5 instead of 3.5. Our sandbox uses the invariant culture (dot as decimal separator); on a real machine, pass CultureInfo.InvariantCulture when you want the same behavior everywhere.

When ReadLine returns null

ReadLine returns null only at the end of the input stream. In a terminal that happens when the user presses Ctrl+Z then Enter (Windows) or Ctrl+D (Linux and macOS), and with redirected input it happens when the file ends. A blank line is not the end: it comes back as an empty string "".

C# Empty line versus end of input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Line 2 is empty, so it prints [] with length 0, and the loop continues. Only after the third line does ReadLine return null. The is null test is the idiomatic way to check; == null works too, but is null cannot be fooled by a type that overloads ==.

A common beginner bug is calling int.Parse(Console.ReadLine()) and getting an ArgumentNullException when the input is empty or ends early. Always decide what your program should do at the end of input: stop, use a default, or print a message.

A validation loop

Programs that talk to people must keep asking until the answer is acceptable. The pattern is a loop that only exits on valid data, and that also stops cleanly if the input ends.

C# Ask until the answer is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The method is a local function declared inside the top-level statements, which is perfectly fine; see Expression-Bodied Members and Local Functions. Three of the four inputs are rejected for different reasons, each with its own message, and the fourth is accepted. Because the helper throws when the input ends, your program never loops forever on a closed input stream: an infinite loop that waits for a null that never changes is a classic bug.

Separate reading from validating from using. A small helper such as ReadInt can be reused for every question your program asks, and the rest of the code can trust that the value is in range.

Several values on one line

Sometimes one line holds several values: 3 4 5. Split the line into parts and parse each part. StringSplitOptions.RemoveEmptyEntries ignores extra spaces, and StringSplitOptions.TrimEntries removes whitespace around each piece.

C# Splitting a line into numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The pattern (line = Console.ReadLine()) is not null assigns and tests in one expression and is the most common shape of a "read until the end" loop. The second line has extra spaces; because of RemoveEmptyEntries, it still splits into just 10 and 20.

Reading everything at once

Instead of a loop you can read the whole input into a single string with Console.In.ReadToEnd(), then split it into lines. This is convenient for small programs and for puzzles where the entire input is data.

C# ReadToEnd and line splitting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ReadToEnd keeps the memory of the entire input, so for very large files prefer reading line by line. Here int.Parse is acceptable because the input format is part of the program's contract; production code would still validate it. The {name,-6} and {count,3} parts are alignment specifiers, covered in the output lesson.

Console.Read and ReadKey

Two more methods exist, and you should know why you usually will not use them:

  • Console.Read() returns the next single character as an int (its UTF-16 code), or -1 at the end of input. You must cast it to char to print it. It is rarely used outside tiny parsers.
  • Console.ReadKey() waits for one key press without Enter. It only works with a real interactive console; when input is redirected it throws InvalidOperationException, and it is unavailable in our editor.

For anything beyond a game or a quick demo, ReadLine is the reliable choice because it works the same for typed and redirected input.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Console.ReadLine() return when the input has ended?

    At the end of the input stream ReadLine returns null. A blank line inside the input is an empty string, which is different.
  2. 2. What is the main difference between int.Parse and int.TryParse for text like "abc"?

    Parse signals bad text with an exception, TryParse reports it with a false return value and leaves 0 in the out variable.
  3. 3. What does Console.WriteLine("20" + "22") print?

    Both operands are strings, so + concatenates them into 2022. Parse them to int first if you want the sum.
  4. 4. Which loop header reads lines until the input ends?

    The assignment-and-test pattern stops exactly when ReadLine returns null. Testing against an empty string would also stop at the first blank line.
  5. 5. Why is a validation loop that never checks for null dangerous?

    After the end of input ReadLine keeps returning null, so a loop that waits for valid data never gets any and never exits.

Summary

  • Console.ReadLine() returns the next line as a string?; it is null only at the end of the input, while a blank line is "".
  • Input is always text. Convert it with Parse (throws on bad text) or TryParse (returns bool); use TryParse for anything a human types.
  • Build validation loops that keep asking until the value is valid and that also stop when the input ends.
  • (line = Console.ReadLine()) is not null is the standard "read until the end" loop.
  • Use Split with RemoveEmptyEntries to read several values from one line, and Console.In.ReadToEnd() for small inputs you want whole.
  • Prefer ReadLine over Read and ReadKey; it behaves the same for typed and redirected input.

Next: The dotnet CLI, Projects and Tooling