Search⌘ K
AI Features

Console I/O

Explore how to manage console input and output in C# by using methods like Console.WriteLine, string interpolation, and tab or newline characters. Learn to read input safely with Console.ReadLine and handle type conversions with TryParse to prevent errors from invalid input.

We have already written several statements that print to the console. This lesson provides examples to consolidate that knowledge.

Console output

Two primary methods handle console output:

  • The Console.Write() method prints to the console and keeps the cursor on the same line.

  • The Console.WriteLine() method prints to the console and moves the cursor to the next line.

Let’s review the following code snippets to see the difference.

C# 14.0
// Because the cursor stays on the same line,
// we have the text printed on the same line
Console.Write("Hello");
Console.Write("World");
  • Lines 3–4: We call Console.Write twice. Because this method does not append a new line character, “World” is printed immediately after “Hello” on the same line.

To make these statements print on separate lines, we can use the Console.WriteLine() method.

C# 14.0
// WriteLine moves the cursor to the next line
// after done printing
Console.WriteLine("Hello");
Console.WriteLine("World");
  • Line 3: Prints “Hello” and moves the cursor to the start of the next line.

  • Line 4: Prints “World” on the new line.

Now, "Hello" and "World" appear on separate lines. However, using the WriteLine() method isn’t the only way we can insert line endings.

Using \n for line breaks

We can use the special \n character for carriage returns. This character serves as a line break when used inside a string literal.

C# 14.0
// Because the cursor stays on the same line,
// we have the text printed on the same line
Console.Write("Hello\n");
Console.WriteLine("World");
Console.Write("One line,\ntwo lines");
  • Line 3: Prints “Hello” followed by a newline character (\n), moving the cursor to the next line manually.

  • Line 4: Prints “World” and moves the cursor to the next line automatically (because it is WriteLine).

  • Line 6: Prints a single string that spans two lines visually because of the embedded \n character.

Using \t for tabs

Besides new-line characters, we can insert \t, which inserts a tab (like pressing the “Tab” key when typing).

C# 14.0
Console.WriteLine("Name\tGrade");
Console.WriteLine("---------------");
Console.WriteLine("Aidil\tC");
Console.WriteLine("Jon\tF");
Console.WriteLine("Patrick\tA");
  • Line 1: Prints headers “Name” and “Grade” separated by a tab.

  • Line 2: Prints “Aidil”, inserts a tab spacing, and then prints “C”.

  • Lines 3–5: Repeat this pattern to align the grades under the header.

String interpolation

There is a way to put variable contents directly inside a string literal. This technique is called string interpolation, and is the best way to print the contents of several variables to the console.

To use interpolation, we place a $ symbol before the opening quotation mark and wrap our variables in curly braces {}.

C# 14.0
string name = "John";
int age = 34;
string country = "USA";
string hobby = "playing sports";
// String interpolation
Console.WriteLine($"Hello. My name is {name} and I am {age} years old.");
Console.WriteLine($"I am from {country} and I love {hobby}");
  • Lines 1–4: We declare and initialize variables for name, age, country, and hobby.

  • Line 7: We use $ before the string. The runtime replaces {name} with "John" and {age} with "34" in the output.

  • Line 8: We repeat the process for country and hobby.

Composite formatting

Another approach is composite formatting, which uses indexed placeholders.

C# 14.0
string name = "John";
int age = 34;
string country = "USA";
string hobby = "playing sports";
// Here we are using numbered placeholders.
Console.WriteLine("Hello. My name is {0} and I am {1} years old.", name, age);
Console.WriteLine("I am from {0} and I love {1}", country, hobby);
  • Line 7: We use {0} and {1} as placeholders. Console.WriteLine replaces {0} with the first argument after the comma (name) and {1} with the second (age).

Console input

The console is the place where we can print and receive information. The Console.ReadLine() method can read data from keyboard input and return a string object once the user presses the “Enter” key.

Look at the example below and provide an input in the box below the code editor. The text entered is fed into the standard input as if we typed this text and pressed “Enter” when Console.ReadLine() executed.

using System;

Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Your name is {name}");
Reading a string from standard input
  • Line 4: The program pauses and waits for user input. Once “Enter” is pressed, the text is stored in the name variable.

  • Line 5: We print the input back to the console using string interpolation.

Note: If we run this code in a modern .NET environment, we might see a warning: CS8600: Converting null literal or possible null value to non-nullable type.

This happens because Console.ReadLine() can theoretically return null (if there is no more input), but our string variable expects a strictly non-null text value. For now, we can safely ignore this warning. We will explore how to handle “nullable” values and ensure type safety later.

The Console.ReadLine() method always returns a string. Therefore, we can only assign it to a variable of the string type by default.

Converting input types

What if we want to obtain the input of other types, like integers and decimals? .NET provides several methods that allow a programmer to convert a value of one type to a value of another type. We can obtain 5 (an int literal) from "5" (a string), for example.

The Convert class has many methods to implement such conversions:

  • The Convert.ToInt32() method converts to int.

  • The Convert.ToDateTime() method converts to DateTime.

  • The Convert.ToBoolean() method converts to bool.

With the help of these methods, we can create an integer variable and store numeric input there.

using System;

Console.Write("Enter your age: ");
string ageString = Console.ReadLine();
int age = Convert.ToInt32(ageString);
Console.WriteLine($"You are {age} years old");
Converting string input into an integer
  • Line 3: We read the input as a string (e.g., “25”).

  • Line 4: We pass ageString to Convert.ToInt32(), which parses the text and returns a numeric int. This is stored in age.

  • Line 5: We print the result. Note that if the input contains letters (like “twenty”), this program will stop with an error because it cannot convert letters to numbers.

Note: If we enter text that is not a number (like “twenty” or “r1”), this program will crash with an error called System.FormatException. This happens because Convert.ToInt32 does not know how to turn letters into numbers. For now, we must be careful to enter only valid numbers. We will learn how to prevent these crashes later.

Safe parsing with TryParse

To prevent our application from crashing when users enter invalid data, modern C# uses the TryParse pattern.

Instead of forcing a conversion, TryParse attempts the conversion and returns a bool indicating whether it succeeded or failed. If it succeeds, it places the converted value into an out variable.

Console.Write("Enter your age: ");
string ageString = Console.ReadLine();

if (int.TryParse(ageString, out int age))
{
    Console.WriteLine($"You are {age} years old.");
}
else
{
    Console.WriteLine("Invalid input. Please enter a valid number.");
}
Safely parsing user input with TryParse
  • Line 4: int.TryParse evaluates ageString. If the string contains a valid integer, it returns true and assigns the numeric value to the newly declared out int age variable.

  • Line 6: This block executes only if the conversion was successful, allowing us to safely use the age variable.

  • Lines 8–11: If the user types letters instead of numbers, TryParse returns false, preventing a crash and allowing us to show a friendly error message.

Using TryParse is the standard best practice for handling typed user input in .NET applications.