Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 182 ยท Getting Started

Console Output and Formatting

Print text in C# with Console.Write and WriteLine, string interpolation, composite formatting, format specifiers (N2, C, P, D, X, E), alignment and Console.Error.

Almost every program has to tell somebody something: a result, a progress message, an error. In a console program that means writing text to the standard output stream. C# gives you Console.WriteLine and Console.Write for the basics and a rich formatting mini-language for turning numbers, dates and other values into exactly the text you want. This lesson covers the writing methods, three ways to put values into text (concatenation, composite formatting and interpolation), the standard and custom format specifiers, alignment for neat tables, the separate error stream, and how to redirect output.

Write and WriteLine

Console.WriteLine writes its argument and then a line break. Console.Write writes without the line break, so the next output continues on the same line.

C# Write versus WriteLine

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.

Both methods accept almost any value. They call ToString() on it, which is why 42, 3.5, True and x all print. Escape sequences inside string literals work as in other languages: \n is a new line, \t a tab, \\ a backslash, \" a double quote. To start a new line differently on every platform, Console.WriteLine() and Environment.NewLine do the right thing for you; do not hard-code \r\n.

Three ways to combine text and values

Suppose you want Total: 3 items, 7.5 EUR. There are three standard approaches, and you will see all of them.

C# Concatenation, composite formatting, interpolation

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.

All three print Total: 3 notebooks, 7.5 EUR. Prefer interpolation (the $"..." form, C# 6). It reads like the output, the compiler checks the expressions, and you cannot mix up the order of placeholders as you can with and . Composite formatting with indexes is still common in older code, in string.Format, and in logging templates. Concatenation with + gets unwieldy beyond a couple of pieces.

To print a literal brace inside an interpolated string, double it: $"{{{count}}}" prints . To use an expression with a colon (for example a conditional), wrap it in parentheses, because the colon otherwise starts a format specifier:

C# Expressions inside interpolation

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.

This prints Status: sold out, Braces: {0}, Math: 42 and Name length: 2.

Format specifiers

After a value inside { } you can add a colon and a format string that controls how the value is turned into text. The same works in composite formatting ({0:N2}) and in ToString("N2").

Standard numeric formats

C# Standard numeric format specifiers

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.

Specifier Meaning Example
N2 Number with group separators and 2 decimals 1,234,567.89
F2 Fixed-point, no separators 1234567.89
C Currency ยค1,234,567.89 in this sandbox
P1 Percent (value times 100) 25.6 % style depends on culture
E3 Scientific notation 1.235E+006
D6 Integer padded with leading zeros 000255
X, x4 Hexadecimal FF, 00ff
B12 Binary 000011111111

Our sandbox uses invariant globalization. Formatting does not depend on an operating-system locale, so N2 always groups thousands with a comma and uses a dot for decimals, and C shows the generic currency sign ยค instead of $ or โ‚ฌ. On a German machine the same {x:N2} would print 1.234.567,89. Use x.ToString("C", someCulture) or set the thread culture when you need a specific one. Interpolation and Formatting covers cultures in depth.

Custom numeric formats

When no standard specifier fits, you can write a pattern: 0 means "a digit, or zero if there is none", # means "a digit, but nothing if it would be a leading or trailing zero", , adds grouping and . marks the decimal point.

C# Custom numeric format patterns

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.

A custom pattern may have up to three sections separated by semicolons: one for positive numbers, one for negative, one for zero. Be careful with rounding in formatting: on .NET 10 here, 2.5.ToString("F0") gives 2 and 3.5.ToString("F0") gives 4, the same ties-to-even result as Math.Round(2.5). If you need to control rounding, round explicitly first (see Floating-Point and decimal).

Dates and other types

Dates have their own specifiers, such as yyyy-MM-dd or HH:mm. Output from DateTime.Now changes every run, so we use a fixed date:

C# Formatting a fixed date and a TimeSpan

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 output is 2025-03-09, 09/03/25 14:05, March 9, 2025, 02:05 PM, 02:15:30 and 2.26 hours. Note the escaped colons in the TimeSpan format: a plain : is a literal only in DateTime formats, not in TimeSpan custom patterns. Enums can print as text, number or hex ({color:G}, {color:D}, {color:X}).

Alignment and padding

A comma and a number after the value set a minimum field width. A positive width right-aligns, a negative width left-aligns, and you can combine it with a format string: {value,10:N2}. This is how you print neat tables.

C# A table with aligned columns

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 names are left-aligned in a 10-character column and numbers right-aligned, which makes the decimals line up. If a value is longer than the width, it is printed in full and the table shifts; widths are minimums. Alternatively use the string methods PadLeft(width) and PadRight(width) (see Working with Strings).

Standard error and redirection

A console program has two output streams: standard output (Console.Out, used by WriteLine) and standard error (Console.Error). Errors, warnings and diagnostics belong on the error stream, so that a user who pipes the output to a file (app > result.txt) still sees the problems on screen, and a script can treat the two differently.

C# Two streams

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.

In our editor both streams appear in the output box, but the error stream is kept apart (it is shown separately or highlighted). In a terminal you can send them to different places with 1>out.txt 2>err.txt.

Inside the program you can also redirect Console.Out yourself with Console.SetOut. That is valuable for tests that check what a method prints, or to capture text that other code writes:

C# Capturing output with SetOut

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 two hidden lines are upper-cased when printed, and the program reports Captured 2 lines. Always restore the original writer, ideally in a finally block.

Colors, beeps and cursor control

A console program can change the color of the text it writes. Set Console.ForegroundColor and Console.BackgroundColor to a member of the ConsoleColor enum (16 colors, such as Red, DarkBlue, Gray), write, and then put the old colors back. Console.ResetColor() restores the defaults the terminal started with.

Always restore colors in a finally block: if the code between throws, the user's terminal would stay green or red after your program ends.

C# Colored status messages

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 lines print their text in the colors above on a real terminal. Our output panel shows plain text, because it is not a terminal, and Console.IsOutputRedirected is true for the same reason. A real console also lets you control more than color:

Member What it does
Console.Write Prints without a newline; use it for prompts such as Console.Write("Name: ")
Console.Clear() Clears the screen (throws when output is redirected)
Console.SetCursorPosition(left, top) Moves the cursor, for simple progress displays and games
Console.CursorVisible Hides or shows the cursor (not supported on every platform)
Console.Title Sets the window title (Windows)
Console.Beep() Plays a short tone on Windows; on Linux and macOS it may only send the bell character
Console.ReadKey(true) Waits for one key without echoing it; needs a real keyboard, see input

Guard these calls when your program might be redirected or run in a service: check Console.IsOutputRedirected first, or wrap them in try/catch (IOException). Colors and cursor tricks are for friendly tools, not for logs, which should stay plain text.

Performance and good habits

  • Console.WriteLine is comparatively slow because it flushes and may talk to a terminal. Writing thousands of lines? Build the text in a StringBuilder (see StringBuilder) and print once.
  • Avoid string concatenation in loops. Interpolation inside a single call is fine.
  • Don't use the console for application logging in services; use a logging framework (Logging).
  • For text that must look the same everywhere (file formats, protocols, logs for machines), format with CultureInfo.InvariantCulture explicitly instead of relying on the machine's culture.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between Console.Write and Console.WriteLine?

    Write leaves the cursor on the same line; WriteLine ends the line.
  2. 2. What does $"{total,10:N2}" do?

    The number after the comma is the minimum field width (positive means right-aligned). The format string after the colon is N2.
  3. 3. How do you print a literal { in an interpolated string?

    Doubling the brace, as in {{ and }}, produces a literal brace in both interpolated and composite formatting strings.
  4. 4. Where should error messages and diagnostics go in a console program?

    Console.Error is the standard error stream, so redirecting standard output to a file does not hide the problems.
  5. 5. What does the format {n:D6} print for the int 255?

    D pads an integer with leading zeros to the requested number of digits.

Summary

  • Console.WriteLine writes a line, Console.Write does not end the line; both convert values with ToString().
  • Prefer interpolation ($"..."); composite formatting () and + concatenation are older alternatives.
  • Format specifiers go after a colon: N2, F2, C, P1, D6, X, E3, B8, plus custom patterns such as 0.00, #,##0 and 000.
  • A comma sets a minimum width: {name,-10} left-aligns, {price,10:N2} right-aligns.
  • Standard error (Console.Error) is separate from standard output; Console.SetOut redirects output for capture or tests.
  • Our sandbox uses invariant culture; other cultures are covered later and are shown read-only.

Next: Reading Input shows how to read what the user types.