String interpolation lets you more easily format strings. String.Format and its cousins are very versatile, but their use is somewhat clunky and error prone. Particularly unfortunate is the use of numbered placeholders like {0} in the format string, which must line up with separately supplied arguments:
var s = String.Format("{0} is {1} year{{s}} old", p.Name, p.Age);
String interpolation lets you put the expressions right in their place, by having “holes” directly in the string literal:
var s = "\{p.Name} is \{p.Age} year{s} old";
Just as with String.Format, optional alignment and format specifiers can be given:
var s = "\{p.Name,20} is \{p.Age:D3} year{s} old";
The contents of the holes can be pretty much any expression, including even other strings:
var s = "\{p.Name} is \{p.Age} year\{(p.Age == 1 ? "" : "s")} old";
Notice that the conditional expression is parenthesized, so that the ‘: “s”’ doesn’t get confused with a format specifier.
Note: This describes the syntax that works in the Preview. However, they have decided to change the syntax, to even better match that of format strings. In a later release you’ll see interpolated strings written like this:
var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old";
They are adding a scheme so that you can influence the formatting behavior; e.g. to use Invariant Culture.
Leave a Reply