C# Input and Output

Build interactive console programs: read what users type with Console.ReadLine, handle empty input and nulls, convert text to numbers safely, keep asking until input is valid, and format output clearly.

Lesson 5 of 43Beginner36 min read

C# input and output is the basic way a console application communicates with the outside world. Input is information the program receives, such as a name, age, quantity, or menu choice. Output is information the program displays, such as instructions, calculated totals, warnings, and results. Learning both makes it possible to turn a fixed program into one that responds to real people.

Think about a simple shopping calculator. Without input, its price and quantity would have to be written directly into the source code. With C# user input, the customer can enter the quantity when the application runs. The program can then calculate the total and show it through console output in C#. The same pattern is used in interactive menus, command-line tools, school projects, and administrative utilities.

The Console class belongs to the System namespace and provides the methods used throughout this lesson. In a modern C# console project, common project settings make Console available without an explicit using System; statement. In older projects or projects without implicit usings, adding using System; makes the class accessible. You can also write System.Console directly.

A useful beginner rule is to separate three tasks: ask for information, check that the answer is usable, and display a meaningful result. Keeping those tasks distinct makes code easier to follow and gives users clearer feedback when they enter something unexpected.

A program becomes much more interesting when it responds to the person using it. Console programs talk to users through the terminal: they **print a prompt, read** what the user types, and print a result. Many real tools work this way, from dotnet and git to small scripts that automate work.

In C#, Console.WriteLine and Console.Write handle output, and **Console.ReadLine reads a whole line of input as a string. The tricky part is that users don't always type what you expect. They might press Enter without typing anything, type "ten" instead of 10, or add extra spaces. Robust programs validate** input and ask again politely instead of crashing.

In this lesson you'll read text and numbers, deal with the nullable result of ReadLine, write a loop that keeps asking until the input is valid, format output so it's easy to read, and read command-line arguments passed when the program starts.

Reading a line of text

Understanding console input in C#

The most common method for taking input in C# is Console.ReadLine(). It reads a complete line from standard input. When someone runs the program in a terminal, standard input is usually connected to the keyboard. The program pauses at ReadLine() until the person presses Enter, then continues using the text it received. The Enter key ends the line; its newline characters are not included in the returned string.

An important detail is that ReadLine() does not know whether the person typed a name, date, number, or other information. It supplies text. If the user enters 25, the initial value is the string "25", not the integer 25. You can display it immediately, but you must convert it before performing numeric calculations. Understanding this distinction prevents many beginner mistakes.

The question mark in string? means the value can be null. Null is different from an empty string: an empty string is a real string containing no characters, while null means no string value was returned. Pressing Enter on a blank line normally gives an empty string. Reaching the end of input, including the end of a redirected file, can produce null instead. A friendly program considers both possibilities rather than assuming there will always be text.

A prompt should make the expected answer obvious. Console.Write() is useful before ReadLine() because the user's cursor stays on the prompt's line. A clear prompt, such as “Enter your city: ”, reduces mistakes. After reading text, Trim() can remove unwanted spaces at either end, but do not automatically remove spaces in situations where they may be meaningful, such as exact user-provided text.

C#

Console.Write("What's your name? ");

string? name = Console.ReadLine();

Console.WriteLine($"Nice to meet you, {name}!");

\- Console.Write keeps the cursor on the same line, which suits prompts.

\- ReadLine waits for the user to press Enter and returns everything they typed, **without** the new line.

\- It returns string? (a string that might be **null**), because input can end, for example when it's redirected from a file. Console.ReadLine() ?? "" replaces null with an empty string.

Reading numbers safely

Converting string input to numbers

To read an integer from the console in C#, first receive the text and then convert it into an int. A conversion method is necessary because arithmetic operators act differently on numeric values and strings. For instance, joining two text values produces combined text, whereas adding two integers produces their numeric sum. Choose the data type based on what the input represents, not simply what it looks like.

C# supports several numeric types. int is suitable for ordinary whole-number quantities and ages; long holds a larger range of whole numbers; double is commonly used for measurements; and decimal is often a better fit for monetary amounts where decimal representation matters. The corresponding TryParse methods let the program test whether a string can be converted to that type.

The difference between int.Parse() and int.TryParse() is especially important for beginners. Parse() returns a number when conversion succeeds but throws an exception if the text has an invalid format. TryParse() instead returns a Boolean result telling you whether conversion worked, while placing the converted value in its out argument. That makes TryParse() a natural default for interactive programs, where wrong answers are normal rather than exceptional events.

Successful conversion is only the first check. A quantity might be a valid integer but still be negative, or an age might be outside the accepted range. C# input validation therefore has two stages: checking the format and checking the meaning. The condition in the lesson does both before accepting the number. This is more helpful than allowing a bad value to travel through the program and cause an incorrect total later.

Numeric parsing also follows culture rules by default. Some regions write decimal values using a comma, while others use a period. A beginner application can use the current culture consistently, but data exchanged with another system often needs an explicitly specified culture. Do not assume every user types decimal points the same way.

Everything typed arrives as text, so numbers must be converted:

C#

Console.Write("How many tickets? ");

string? text = Console.ReadLine();



if (int.TryParse(text, out int tickets) && tickets > 0)

{

    Console.WriteLine($"Booking {tickets} tickets");

}

else

{

    Console.WriteLine("Please enter a positive whole number.");

}

TryParse returns false for empty, null or invalid text instead of throwing an exception, so it's the right choice for anything a person types. Use double.TryParse or decimal.TryParse for decimals.

Asking until the input is valid

Repeating a prompt with input validation

A C# input validation loop makes a program much easier to use. Instead of ending after one incorrect answer, it asks again until the user supplies something acceptable. This is useful for an age field, a ticket quantity, a menu selection, or any choice with a defined set of valid values. The user receives immediate guidance and can correct the mistake without restarting the application.

The sample uses a while (true) loop and a break statement. At first this might seem like a loop that never ends, but break exits when both parsing and the range check succeed. The error message runs only if the input fails. Notice how the message tells the person exactly what is allowed; “Please enter an age between 0 and 120” is more useful than a vague “Error.”

For larger console programs, repeated validation logic belongs in a helper method. A method that reads a bounded integer can be reused for a customer's quantity, an employee's age, or a menu option by changing its prompt and minimum and maximum values. This keeps the main program focused on what it does rather than how every answer is checked.

There is one extra case to consider in production: an input stream may end permanently. If Console.ReadLine() returns null in a loop that always retries, the program may repeatedly print errors without receiving new input. When a console program processes redirected or piped input, handle null as a signal to stop, use a default, or report that no more data is available. Interactive applications can decide how to exit when the user cannot provide another answer.

Wrap the prompt in a loop that only ends when the input is acceptable:

C#

int age;

while (true)

{

    Console.Write("Age: ");

    if (int.TryParse(Console.ReadLine(), out age) && age is >= 0 and <= 120)

        break;

    Console.WriteLine("Please enter an age between 0 and 120.");

}

age is >= 0 and <= 120 is a **pattern** that checks a range in one readable expression. Putting this logic in a helper method, such as ReadInt(string prompt, int min, int max), keeps the rest of the program tidy.

Command-line arguments and extras

Console.Read(), Console.ReadKey(), and command-line input

Not every C# application needs a complete line of text. Console.Read() reads the next character from standard input and returns its numeric character code, or -1 at the end of the stream. It can be useful when you need to process input character by character, although ReadLine() is usually easier for beginners. Console.ReadKey() works differently: it waits for a key press and returns information about the key, including the Key and KeyChar properties. It is suitable for simple interactive menus or a “press any key” message in a real terminal.

C# command-line arguments are another kind of input. They are supplied when the program starts, before the program calls ReadLine(). In top-level statements, the args array contains these values as strings. Arguments are useful for specifying an input filename, choosing an operation, or passing a setting to an automation script. They do not replace interactive prompts; they simply provide a convenient noninteractive option.

Always check args.Length before accessing an element. Otherwise, asking for args[0] when the user did not supply any argument causes an exception. Arguments containing spaces may need quoting in the shell. They also arrive as strings, so a numeric argument needs the same parsing and validation as a value entered at a prompt.

Console appearance can improve readability, but it should support the message rather than carry all its meaning. Console.ForegroundColor and Console.BackgroundColor can emphasize headings or errors, and Console.ResetColor() returns to the previous defaults. Console.Clear() can clear a terminal screen, but its behavior depends on the host and may not work when the output is redirected. A readable message should still make sense without color.

Values typed after the program name arrive in args: running dotnet run -- report.csv 10 gives args[0] == "report.csv" and args[1] == "10". Check args.Length before using them.

\- Console.ReadKey() reads a single key press without Enter, useful for menus.

\- Console.ForegroundColor = ConsoleColor.Green; changes the text colour, and Console.ResetColor() restores it.

\- Console.Clear() clears the screen.

Reading until the input ends

Processing multiple lines and redirected input

A console program can receive information from a file or another program instead of a person typing at the keyboard. The idea is called standard input redirection. Your C# code can still call Console.ReadLine() normally; it does not need to know whether the source is interactive. This makes basic input and output programs surprisingly useful for scripts and automated tasks.

When reading many lines, the program needs a stopping rule. In a redirected stream, the natural stopping point is the end of input, when ReadLine() returns null. A loop can read one line, check or convert it, process it, and then continue to the next line. This style is especially useful for counting records, adding quantities, and examining text files. The important distinction is that an empty line is not the same as the end of the stream: you may choose to skip an empty line and continue reading.

The sample accepts lines that can be parsed as integers and adds them together. In a different application you might instead report which lines are invalid, keep a count of rejected lines, or stop if an unexpected value appears. The correct behavior depends on what the program promises its users. For a learning example, ignoring invalid lines is simple; for financial or business data, silent skipping could hide an error.

Pipelines and redirection are particularly helpful when testing. You can prepare a small file with normal input, blank lines, and invalid values, then run the program repeatedly using the same data. That makes bugs easier to reproduce than manually entering a different sequence every time. This is one reason even small console tools benefit from clear input rules and predictable output.

ReadLine returns null when there's no more input. That happens when someone presses Ctrl+Z then Enter on Windows or Ctrl+D on macOS and Linux, and when input comes from a file. You can use it to process any number of lines:

C#

int total = 0;

string? line;

while ((line = Console.ReadLine()) != null)

{

    if (int.TryParse(line, out int n))

        total += n;

}

Console.WriteLine($"Total: {total}");

Run it with dotnet run < numbers.txt and the program reads the file as if someone had typed each line. Redirecting input like this is a quick way to test a console program without typing the same values over and over.

Error output and exit codes

Standard output, standard error, and exit status

C# console output normally goes through the standard output stream. That is where Console.Write() and Console.WriteLine() send regular information and results. A separate standard error stream is intended for warnings and failures. You can write to it using Console.Error.WriteLine(). In a terminal, both streams often appear in the same window, so the distinction may be invisible at first.

Separating these streams matters when someone redirects a command's output into a file or another program. A useful tool may print only its final result on standard output and send troubleshooting messages to standard error. This prevents a later program from mistaking “File not found” for a data record. It also makes the tool easier to combine with other commands.

An exit code is a small status value returned when a console application ends. By convention, zero indicates success and a nonzero value indicates failure. Automation systems and shell scripts can check the code to decide whether the next step should run. Beginners can start with a simple success-or-failure distinction, then introduce additional codes only when there is a clear reason.

For code that will be used by other programs, be consistent: print useful data to standard output, explain problems on standard error, and return an appropriate exit code. For a casual interactive program, friendly on-screen messages may be enough. Both styles use the same underlying Console functionality; they simply serve different audiences.

Programs have two output streams. Console.WriteLine writes to **standard output, and Console.Error.WriteLine writes to standard error**. Both appear in the terminal, but when a user saves your output to a file with > results.txt, error messages still show on screen instead of mixing with the results.

A program also finishes with an **exit code**: 0 means success and anything else means something went wrong. Scripts and build tools check this number. With top-level statements, you can simply return it:

C#

if (args.Length == 0)

{

    Console.Error.WriteLine("Usage: report <file>");

    return 1;

}

Console.WriteLine($"Reading {args[0]}");

return 0;

In a classic program, declare static int Main(string[] args) and return the code in the same way.

Console.Write vs Console.WriteLine

Both Console.Write() and Console.WriteLine() send information to the terminal, but they differ in what happens after the text. Write() leaves the cursor on the same line, so the next output or user input can appear immediately after the message. This makes it a natural choice for prompts. WriteLine() adds a line ending, so following output starts on the next line. It works well for headings, results, lists, and explanations.

Neither method is limited to string variables. They support common values such as integers, decimals, and Boolean values through their available overloads. An overload is a version of a method that accepts a particular set of arguments. C# selects the appropriate version based on what you pass. You can therefore display a calculated number without converting it into text manually first.

For neatly formatted output, C# string interpolation is often easiest to read. A string beginning with $ can contain variable names and expressions inside braces. When the message is produced, those placeholders become their evaluated values. You can also add a numeric format after a colon to control decimal places, percentages, or thousands separators. Formatting changes the displayed text, not the number stored in the variable.

Keep the audience in mind when choosing output. A human reading a receipt benefits from labels, spacing, and currency formatting. A script reading program output may need one consistent value per line. Good formatting is not merely decoration; it communicates what each result means and makes mistakes easier to notice.

Different types of user input in C#

A single console method can support several kinds of information because Console.ReadLine() reads text first. Afterward, the program decides how to interpret that text. For a person's name, you may keep it as a string. For a count of items, parse an integer. For a measurement, try a floating-point type. For an amount of money, consider decimal. For a true-or-false setting, bool.TryParse() recognizes the Boolean words true and false, while a custom yes-or-no prompt may need its own rules.

A single character also deserves care. char.TryParse() succeeds only when the supplied string represents exactly one UTF-16 char. A name or a multi-character answer cannot fit in that type. If you want one menu selection, decide whether to read a line and validate its length or use ReadKey() to respond immediately to a key press.

Some applications require dates and times as well. The general pattern is similar: read the text, use a suitable TryParse() method, and check whether the result makes sense for the task. For important dates, specify an expected format when necessary instead of assuming everyone enters dates in the same order. The key lesson is that reading text and interpreting text are separate operations.

When an input cannot be converted, do not build the rest of the program around an unverified value. Tell the user what format is expected or stop cleanly when input comes from a file. This small habit makes programs much more reliable as they grow.

Common console input mistakes and good practices

One frequent mistake is confusing Console.ReadLine() with Console.WriteLine(). The names look similar but their roles are opposite: one receives a line, and the other displays a line. Another mistake is assuming that typed digits automatically become numbers. They do not. C# input conversion must happen before arithmetic, comparisons, or range checks that need numeric values.

A third mistake is relying on Parse() for unpredictable user input. It is appropriate when malformed data should be treated as an exceptional failure, but a person typing a wrong answer is routine. TryParse() gives your program control over the response. You can display a helpful message and continue without showing a technical exception to the user.

Beginners also sometimes forget that a nullable result is possible. Calling string members directly on null can cause a runtime error. Use a null check, the null-coalescing operator, or a deliberate end-of-input path depending on the situation. Choosing an empty string as a fallback is reasonable for an optional name, but it may hide missing data when a value is required.

Finally, be careful with repeated prompts and output presentation. A loop should have a clear success condition and, where necessary, a way to stop when input ends. Errors should be specific and polite. Output should contain useful labels, and important messages should not depend entirely on console colors, which may vary between terminals or disappear during redirection. These practices help make an introductory console exercise feel like a dependable small application.

C# Basics Syntax

Input and output


Console.Write("Prompt: ");

string input = Console.ReadLine() ?? "";

string clean = input.Trim();

if (int.TryParse(clean, out int n)) { /* use n */ }

if (decimal.TryParse(clean, out decimal amount)) { }

bool yes = clean.Equals("y", StringComparison.OrdinalIgnoreCase);

ConsoleKeyInfo key = Console.ReadKey();

Console.ForegroundColor = ConsoleColor.Red;

Console.ResetColor();

if (args.Length > 0) Console.WriteLine(args[0]);

C# Basics Summary

\- Console.Write prints a prompt; Console.ReadLine reads a line as string?.

\- Use ?? to replace a null result with a default.

\- Convert input with int.TryParse or decimal.TryParse, never assuming it's valid.

\- Loop until input passes validation, with a clear message each time.

\- Command-line arguments arrive in args; check args.Length first.

C# Basics Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A greeting with a default

\- 2: ?. trims only if the result isn't null, and ?? supplies an empty string if it is.

\- 4-7: An empty answer is replaced with a friendly default.

\- 9-10: The output shows a run where the user typed Grace.

C#

Console.Write("Name (press Enter to skip): ");

string name = Console.ReadLine()?.Trim() ?? "";



if (string.IsNullOrWhiteSpace(name))

{

    name = "friend";

}



Console.WriteLine($"Hello, {name}!");

Console.WriteLine($"Your name has {name.Length} letters.");
Output

Name (press Enter to skip): Grace

Hello, Grace!

Your name has 5 letters.
Example 2

A validated number

\- 1: A local function keeps the validation logic in one reusable place.

\- 3: The loop only ends when return runs.

\- 7: Both the conversion and the range must pass.

\- 15: The caller gets a valid number without worrying about bad input.

\- 17: :F2 formats both amounts with two decimal places.

C#

int ReadInt(string prompt, int min, int max)

{

    while (true)

    {

        Console.Write(prompt);

        string? text = Console.ReadLine();

        if (int.TryParse(text, out int value) && value >= min && value <= max)

        {

            return value;

        }

        Console.WriteLine($"Please enter a whole number from {min} to {max}.");

    }

}



int qty = ReadInt("Quantity (1-10): ", 1, 10);

decimal price = 4.50m;

Console.WriteLine($"{qty} x {price:F2} = {qty * price:F2}");
Output

Quantity (1-10): lots

Please enter a whole number from 1 to 10.

Quantity (1-10): 25

Please enter a whole number from 1 to 10.

Quantity (1-10): 3

3 x 4.50 = 13.50
Example 3

A yes or no menu with arguments

\- 1: The output shows a run started with dotnet run -- maria; without an argument the user is "guest".

\- 5: Trimming and lowercasing means "YES", " y " and "Yes" all work.

\- 7: The or pattern checks two values at once.

\- 9-11: The text turns green, and ResetColor restores the normal colour.

C#

string user = args.Length > 0 ? args[0] : "guest";

Console.WriteLine($"Signed in as {user}");



Console.Write("Show the report? (y/n): ");

string answer = (Console.ReadLine() ?? "").Trim().ToLower();



if (answer is "y" or "yes")

{

    Console.ForegroundColor = ConsoleColor.Green;

    Console.WriteLine("Sales: 1,204 orders this week");

    Console.ResetColor();

}

else

{

    Console.WriteLine("Report skipped.");

}
Output

Signed in as maria

Show the report? (y/n): YES

Sales: 1,204 orders this week

Common C# Basics Mistakes

int.Parse on user input

Don't

int age = int.Parse(Console.ReadLine());   // crashes with FormatException on "abc"
Do

if (!int.TryParse(Console.ReadLine(), out int age))

{

    Console.WriteLine("Please type a number.");

}

Ignoring the possible null

Don't

string name = Console.ReadLine();        // warning CS8600: converting null to non-nullable type

Console.WriteLine(name.ToUpper());       // could throw NullReferenceException
Do

string name = Console.ReadLine() ?? "";

Console.WriteLine(name.ToUpper());

Reading args without checking

Don't

string file = args[0];                   // IndexOutOfRangeException when no argument is given
Do

if (args.Length == 0)

{

    Console.WriteLine("Usage: report <file>");

    return;

}

string file = args[0];

C# Basics in Real Projects

Console apps in practice

Console programs remain useful even when an application has a website or graphical interface. Developers use them for scheduled maintenance, data imports, quick reports, build pipelines, testing utilities, and one-time administration. In each case, the same fundamentals appear: receive input, validate it, perform a task, and write a result that someone can understand or another program can process.

For beginners, a good next project is a small order calculator. Ask for a product name and quantity, validate the quantity, calculate a total, and print a neat receipt. Then extend it to accept a filename or price as a command-line argument. That project combines user input, data conversion, loops, formatted console output, and error handling without requiring a graphical interface.

Developers write console tools to import data, run database migrations, clean up files and call APIs on a schedule. They take settings from command-line arguments, validate everything carefully, and print clear progress and errors. Libraries such as System.CommandLine and Spectre.Console add argument parsing, coloured tables and progress bars to the same basic ideas.

C# Basics FAQ

Why does Console.ReadLine return a nullable string?

ReadLine returns null when the input stream ends, for example when input is redirected from a file that has no more lines. The ? warns you about this so you handle it, either with ?? "" or a null check. When a person is typing interactively, you normally get a string, even an empty one.

How do I read an integer from the console in C#?

Read the line with Console.ReadLine() and convert it with int.TryParse, which returns false instead of throwing when the text isn't a valid number. Put the prompt in a loop so the user can try again after a mistake. int.Parse works too, but crashes with a FormatException on input such as "ten".

How do I pass command-line arguments with dotnet run?

Put them after a double dash: dotnet run -- input.txt 5. Everything after -- goes to your program in the args array, so args[0] is "input.txt" and args[1] is "5". Without the --, dotnet may try to treat them as its own options.

How do I wait for a key press before the console closes?

Add Console.ReadKey(); at the end of the program; it waits for one key and doesn't need Enter. This is mainly useful when a program is started by double-clicking, because the window closes as soon as the program ends. When you run from a terminal, the output stays visible anyway.

How do I print coloured text in the console?

Set Console.ForegroundColor to a value such as ConsoleColor.Red, write your text, then call Console.ResetColor() so later output goes back to normal. Console.BackgroundColor changes the background in the same way. Colours appear in most terminals but are lost when the output is redirected to a file.

C# Basics Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the line that reads what the user types.


string? text = Console.\();
Multiple choiceeasy

What type does Console.ReadLine return?

\- [ ] int

\- [x] string? (a string that may be null)

\- [ ] char

\- [ ] object

Predict the outputmedium

The user types  42 . What does this print?

\- [x] 43

\- [ ] -1

\- [ ] 421

\- [ ] 42


bool ok = int.TryParse(Console.ReadLine(), out int n);

Console.WriteLine(ok ? n + 1 : -1);
Multiple choicemedium

What does Console.ReadLine() ?? "" do?

\- [ ] Removes spaces

\- [ ] Converts to a number

\- [x] Uses an empty string if ReadLine returns null

\- [ ] Repeats the prompt

Multiple choicehard

How do you pass "data.csv" to args[0]?

\- [ ] dotnet run data.csv --

\- [ ] dotnet data.csv run

\- [ ] args = "data.csv"

\- [x] dotnet run -- data.csv

C# Basics Quiz

5 questions to check what you learned.

  1. Which method prints without moving to a new line?

    \- [ ] Console.WriteLine

    \- [x] Console.Write

    \- [ ] Console.Print

    \- [ ] Console.Out

    • Why use int.TryParse rather than int.Parse for user input?

      \- [ ] It's shorter

      \- [ ] It accepts decimals

      \- [ ] It reads from the console automatically

      \- [x] It returns false for invalid text instead of throwing an exception

      • What does Console.ReadKey do?

        \- [x] Reads a single key press

        \- [ ] Reads a whole line

        \- [ ] Reads a file

        \- [ ] Returns the last key typed earlier

        • What does answer is "y" or "yes" check?

          \- [ ] That answer contains y

          \- [ ] That answer is a bool

          \- [x] That answer equals "y" or equals "yes"

          \- [ ] Nothing, it's invalid

          • How do you restore the console's normal colour after changing it?

            \- [ ] Console.Clear()

            \- [x] Console.ResetColor()

            \- [ ] Console.ForegroundColor = null

            \- [ ] Restart the program