Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The Console class

Reference for System.Console in C#: Write, WriteLine, Error, In and Out streams, redirection with SetOut, encodings, IsOutputRedirected and exit codes.

System.Console is the static class behind every "Hello, World" program. It connects your code to the three standard streams of the process: standard output (Console.Out), standard error (Console.Error) and standard input (Console.In). Console.Write and Console.WriteLine are shortcuts for Console.Out.Write and WriteLine, and Console.ReadLine reads from Console.In.

Because the three streams are ordinary TextWriter and TextReader objects, you can swap them: Console.SetOut sends output to a StringWriter for a test, or to a file. The class also tells you whether a stream is attached to a terminal or redirected to a pipe or file, which decides whether features such as cursor movement and key reads are possible.

C#
Console.WriteLine("result");           // stdout
Console.Error.WriteLine("warning");    // stderr
string? line = Console.ReadLine();     // stdin, null at end of input

Try it

C# Write, WriteLine and formatting

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.

C# Redirecting 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.

Syntax

C#
public static TextWriter Out { get; }
public static TextWriter Error { get; }
public static TextReader In { get; }

public static void Write(...);        // many overloads
public static void WriteLine(...);
public static string? ReadLine();
public static int Read();

public static void SetOut(TextWriter newOut);
public static void SetError(TextWriter newError);
public static void SetIn(TextReader newIn);
public static Stream OpenStandardOutput();
public static Stream OpenStandardInput();

public static bool IsOutputRedirected { get; }
public static bool IsInputRedirected { get; }
public static bool IsErrorRedirected { get; }
public static Encoding OutputEncoding { get; set; }
Member Description
Write / WriteLine Write any primitive, a string, char[], an object (its ToString()), or a composite format string with arguments. WriteLine appends Environment.NewLine.
Out, Error, In The current writer or reader for each stream.
SetOut, SetError, SetIn Replace the stream. SetOut(null) throws ArgumentNullException; use TextWriter.Null to discard output.
OpenStandardOutput() and friends The raw byte Stream, for binary data.
IsOutputRedirected etc. true when the stream is a pipe or file, not an interactive terminal.
OutputEncoding / InputEncoding Text encoding used for the streams (UTF-8 on most systems today).
Environment.ExitCode The exit code returned when Main finishes; Environment.Exit(n) ends immediately.

Returns: ReadLine() returns null at end of input; Read() returns -1.

Errors: IOException if the stream is closed or broken (for example | head closing a pipe), InvalidOperationException for key-reading and cursor members when no real console exists.

Usage notes

  • Console.Out is synchronized and auto-flushed. Every Write call is thread-safe and flushed right away, which is convenient but slow for huge output. Wrap OpenStandardOutput() in a buffered StreamWriter when you print millions of lines.
  • Errors belong on Error. Keep results on standard output and diagnostics on standard error so users can pipe results (prog > out.txt) without mixing in messages.
  • Test output with SetOut. Capturing into a StringWriter lets you assert on what a method prints. Restore the original in a finally block, and do not use it in tests that run in parallel, because Console.Out is process-wide.
  • Composite formats are culture-aware. Numbers print according to the current culture. Pass CultureInfo.InvariantCulture (string.Create, or FormattableString.Invariant) for machine-readable output.
  • Encoding. Old Windows consoles may need Console.OutputEncoding = Encoding.UTF8 to show non-ASCII text. On Linux and macOS UTF-8 is the default.
  • Ctrl+C. Console.CancelKeyPress lets you shut down gracefully; set e.Cancel = true to continue running.
  • Exit codes. Return an int from Main, or set Environment.ExitCode. By convention 0 means success.
  • Not for services. Web apps and background services should log through ILogger, which can target the console among other sinks.