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.
Lines 3–4: We call
Console.Writetwice. 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.
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.
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
\ncharacter.
Using \t for tabs
Besides new-line characters, we can insert \t, which inserts a tab (like pressing the “Tab” key when typing).
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 {}.
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
countryandhobby.
Composite formatting
Another approach is composite formatting, which uses indexed placeholders.
Line 7: We use
{0}and{1}as placeholders.Console.WriteLinereplaces{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}");Line 4: The program pauses and waits for user input. Once “Enter” is pressed, the text is stored in the
namevariable.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 toint.The
Convert.ToDateTime()method converts toDateTime.The
Convert.ToBoolean()method converts tobool.
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");Line 3: We read the input as a string (e.g., “25”).
Line 4: We pass
ageStringtoConvert.ToInt32(), which parses the text and returns a numericint. This is stored inage.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.");
}Line 4:
int.TryParseevaluatesageString. If the string contains a valid integer, it returnstrueand assigns the numeric value to the newly declaredout int agevariable.Line 6: This block executes only if the conversion was successful, allowing us to safely use the
agevariable.Lines 8–11: If the user types letters instead of numbers,
TryParsereturnsfalse, 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.