Console formatting
Learn formatting with WriteLine format strings and alignment.
String interpolation
The easiest way to embed variables into a string in C# is string interpolation. You put a $ sign before the string and place variables inside {}. It is far more readable than concatenating with +.
For example, $"Hello, {name}!" inserts the value of name into the string. You can also write simple expressions inside the braces: $"Total: {a + b}". This is the most common style in modern C#.
Alignment and format specifiers
In interpolation, you can write {expr,width} inside the braces to align a value to a certain width. A negative width left-aligns, a positive width right-aligns. You can also add format specifiers like {expr:F2}.
For example, $"{name,-10}!" left-aligns name to 10 characters. $"{price:F2}" shows the price with two decimal places. This feature is perfect for producing tabular output.
Formatting with ToString
When converting a value to a string, you can pass a format specifier to the ToString method. F2 gives two decimal places, C gives currency, X gives hexadecimal. This is used to print numbers readably.
For example, (3.1415).ToString("F2") returns "3.14". (255).ToString("X") gives "FF". You can apply the same format in interpolation with {price:F2}.
Exercise Print the total with interpolation
Use quantity and price in a Console.WriteLine with string interpolation. The output should be "<quantity> items, total <quantity * price> USD". Use a multiplication expression inside the curly braces.
Show example solution
Print with Console.WriteLine($"{quantity} items, total {quantity * price} USD");
Example solution:
using System;
class Program
{
static void Main()
{
int quantity = 3;
int price = 25;
Console.WriteLine($"{quantity} items, total {quantity * price} USD");
}
}
Test yourself
-
Which one is string interpolation?
string name = "Alex";- string.Format("Hello, {0}!", name)
- $"Hello, {name}!"
- "Hello, " + name
- Console.WriteLine("Hello")
Show answer
$"Hello, {name}!" — Correct! The $ prefix and {} make interpolation.
-
Left-aligned output
string name = "Alex"; Console.WriteLine(____);Show answer
string name = "Alex"; Console.WriteLine($"{name,-10}!"); -
Match the format with its output
- ToString("F2")
- 3.14
- ToString("X")
- FF
- {name,-10}
- left-aligned