LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1215 min read

Input & Output

Learn how to read console input and format output using Console.ReadLine, WriteLine, and string interpolation.

Console.WriteLine & Console.Write

`Console.WriteLine` prints text followed by a new line. `Console.Write` prints without a line break, useful for prompts where you want the user's response to appear on the same line.

Console.Write("Enter your age: ");
Console.WriteLine("This appears on a new line after input.");

Console.ReadLine

`Console.ReadLine()` reads a full line of text typed by the user (up until they press Enter) and always returns a `string?` (nullable), so numeric input needs converting — as covered in the type conversion lesson, TryParse is the safer choice for real user input.

Console.Write("Enter your age: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age))
{
Console.WriteLine($"Next year you'll be {age + 1}.");
}
else
{
Console.WriteLine("That doesn't look like a valid age.");
}

Console.ReadKey

Unlike ReadLine (which waits for Enter), Console.ReadKey() reads a single keypress immediately, without needing Enter pressed afterward — useful for "Press any key to continue" prompts or simple menu navigation.

Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Console.WriteLine("\nContinuing!");

String Interpolation

The `$` prefix lets you embed expressions directly inside a string using curly braces — far more readable than manual string concatenation with the + operator, and it can embed any valid C# expression, not just simple variables.

string name = "Priya";
int score = 92;
Console.WriteLine($"{name} scored {score}% — {(score >= 90 ? "Excellent" : "Good")}!");
Output

Click Run to see what this code prints.

Fun Fact

String interpolation, introduced in C# 6.0 (2015), compiles down to a call to string.Format() behind the scenes — it is purely a more readable syntax for something already possible, not a fundamentally new capability.

Format Specifiers

A colon inside an interpolated expression applies a format specifier, controlling exactly how a value displays — essential for currency, percentages, and controlling decimal places.

SpecifierMeaningExampleResult
CCurrency{19.9:C}$19.90
N2Number, 2 decimal places, with thousands separators{1234.5:N2}1,234.50
PPercentage{0.256:P}25.60%
D4Integer padded to 4 digits{7:D4}0007
XHexadecimal{255:X}FF
decimal price = 1234.5m;
Console.WriteLine($"{price:C}"); // $1,234.50
Console.WriteLine($"{price:N2}"); // 1,234.50
Console.WriteLine($"{0.256:P}"); // 25.60%

Alignment can also be controlled with a comma inside the braces — a positive number right-aligns within that many characters, negative left-aligns, useful for building neatly columned console output.

Console.WriteLine($"{"Name",-10}{"Score",5}");
Console.WriteLine($"{"Priya",-10}{92,5}");
Console.WriteLine($"{"Alex",-10}{78,5}");
Output

Click Run to see what this code prints.

Escape Sequences & Verbatim Strings

A backslash inside a regular string introduces an escape sequence — a way to represent characters that would otherwise be hard or impossible to type directly.

SequenceMeaning
\nNew line
\tTab
\"A literal double quote inside a double-quoted string
\\A literal single backslash

For strings containing many backslashes (like a Windows file path), a verbatim string — prefixed with @ — treats backslashes as literal characters, removing the need to escape them.

string regular = "C:\\Users\\Alex\\Documents"; // every backslash must be doubled
string verbatim = @"C:\Users\Alex\Documents"; // reads naturally, no escaping needed

Colored Console Output

Console.ForegroundColor and Console.BackgroundColor let you color console text — a small but genuinely useful touch for CLI tools that highlight errors, warnings, or success messages.

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: something went wrong.");
Console.ResetColor(); // always reset afterward, or every later line stays red too!
Always Call ResetColor()

Forgetting to reset the console color leaks it into every subsequent line of output — including output from entirely unrelated parts of your program — until something else explicitly resets it.

A Complete Example

Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int number))
{
Console.WriteLine($"Double of {number} is {number * 2}.");
}
else
{
Console.WriteLine("That wasn't a valid number.");
}

Common Beginner Mistakes

Forcefully unwrapping ReadLine() with ! without checking for null first

Console.ReadLine()! tells the compiler "trust me, this isn't null" — but if input actually is redirected from an exhausted file/pipe, this throws a NullReferenceException at runtime instead of handling it gracefully.

Concatenating strings with + instead of interpolation

"Score: " + score + "%" works, but becomes hard to read with more than a couple of values — $"Score: {score}%" is clearer and is the modern convention.

Forgetting to double backslashes in a regular (non-verbatim) string

A Windows path like "C:\Users" needs to be written as "C:\\Users" in a regular string, or simply as a verbatim string: @"C:\Users".

FAQs

Because it returns `null` if the input stream has ended (like when input is redirected from a file that runs out of lines) — the compiler forces you to account for that possibility rather than assuming input is always available.

Write does not append a newline afterward, so subsequent output continues on the same line; WriteLine always moves to a new line after printing.

Yes — {price,10:C} both right-aligns within 10 characters and formats as currency, in that order.

Not directly from Console.ReadLine() — it always returns a string, since the console has no concept of typed input; conversion is always a separate step.

Key Takeaways

  • Console.WriteLine/Write handle output; ReadLine handles input (as a string); ReadKey reads a single keypress immediately.
  • ReadLine() always returns a nullable string — never force-unwrap it without validating first.
  • String interpolation ($"...") is the cleanest way to build formatted output, and supports format specifiers ({value:C}) and alignment ({value,10}).
  • Verbatim strings (@"...") avoid needing to escape backslashes, ideal for file paths.

Summary

Console I/O and string formatting are the tools you'll reach for constantly while building and debugging every program in this course. Next, you'll learn how to make your programs actually make decisions with conditional statements.

Next Lesson →

Conditional Statements