TExcelTAD
Home › C# › C# Output

C# Output

Console programs talk to the user by writing text to the standard output. In C# that is done with the static methods of the System.Console class.

WriteLine and Write

Method Behaviour
Console.WriteLine(x) Prints x and then moves to a new line
Console.WriteLine() Prints just an empty line
Console.Write(x) Prints x and stays on the same line
csharp · try it yourself
using System;

Console.Write("Loading");
Console.Write(".");
Console.Write(".");
Console.WriteLine(".");
Console.WriteLine();
Console.WriteLine("Done!");
Loading...

Done!

Printing numbers and expressions

WriteLine accepts almost any value — numbers, booleans, characters — and converts it to text for you. If you pass an expression, it is evaluated first.

csharp · try it yourself
using System;

Console.WriteLine(42);
Console.WriteLine(3.5);
Console.WriteLine(10 + 5);
Console.WriteLine(7 > 3);
Console.WriteLine('A');
42
3.5
15
True
A

Notice that bool values print as True and False with a capital letter.

Combining text and values

There are three common ways to mix text with values. All three print the same line:

csharp · try it yourself
using System;

string name = "Ada";
int age = 36;

// 1. Concatenation with +
Console.WriteLine("Name: " + name + ", age: " + age);

// 2. Composite formatting with numbered placeholders
Console.WriteLine("Name: {0}, age: {1}", name, age);

// 3. String interpolation (recommended)
Console.WriteLine(
quot;Name: {name}, age: {age}");
Name: Ada, age: 36
Name: Ada, age: 36
Name: Ada, age: 36

String interpolation — a $ before the string and expressions in { } — is the most readable option and is used throughout this tutorial. It has its own lesson later.

Note: Be careful with + and numbers: "Sum: " + 2 + 3 gives Sum: 23, because the text is concatenated left to right. Write "Sum: " + (2 + 3) to add first.

Escape sequences

Some characters cannot be typed directly inside a string literal. Use a backslash escape sequence instead:

Sequence Meaning
\n New line
\t Tab
\" Double quote
\\ Backslash
csharp · try it yourself
using System;

Console.WriteLine("Line one\nLine two");
Console.WriteLine("Name\tScore");
Console.WriteLine("She said \"hi\"");
Console.WriteLine("C:\\Users\\ada");
Console.WriteLine(@"C:\Users\ada");
Line one
Line two
Name	Score
She said "hi"
C:\Users\ada
C:\Users\ada

The last line uses a verbatim string (@"..."), in which backslashes are taken literally — handy for Windows paths and regular expressions.

Test yourself

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

  1. Write is faster
  2. WriteLine adds a new line after the text
  3. Write only accepts strings
  4. There is no difference

What does Console.WriteLine("Total: " + 4 + 1); print?

  1. Total: 5
  2. Total: 41
  3. Total: 4 1
  4. A compile error

Which escape sequence inserts a tab?

  1. \n
  2. \t
  3. \b
  4. \s