String interpolation in C#
The $ string is C#'s template: expressions, formats and alignment inline.
var name = "Grace";
var items = 3;
var total = 42.5;
// $ turns a string into a template; the braces hold any expression
Console.WriteLine($"{name} bought {items} items");
Console.WriteLine($"total: {total:F2}, half: {total / 2:F1}");
// alignment pads a column: negative left-aligns, positive right-aligns
Console.WriteLine($"|{name,-10}|{items,5}|");
How it works
- A
$prefix turns braces into holes for any expression. :F2and:F1format numbers to fixed decimal places.{name,-10}pads a column: negative left-aligns, positive right-aligns.
Keywords and builtins used here
var
The run, in numbers
- Lines
- 10
- Characters to type
- 354
- Tokens
- 38
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 24 seconds.
Step 1 of 4 in Strings, step 4 of 29 in Language basics.