C#6 – String interpolations

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: