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 |
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.
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:
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 + 3givesSum: 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 |
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?
Writeis fasterWriteLineadds a new line after the textWriteonly accepts strings- There is no difference
What does Console.WriteLine("Total: " + 4 + 1); print?
- Total: 5
- Total: 41
- Total: 4 1
- A compile error
Which escape sequence inserts a tab?
- \n
- \t
- \b
- \s