String interpolation

This is one of a series of posts on some of the new features in C# 6.0, which was just released.

The ability to format strings in .NET is straightforward, and fairly powerful (ignore the line breaks):

string value = string.Format("My name is {0}, and I was born in 
    {1:yyyy}", ob.Name, ob.Birthday);

Note that you can have multiple arguments, and you can add various formatting options to control the display. One downside with this approach, however, is that it is easy to mess up — when you add, remove or change the arguments, the various placeholders might not line up correctly, which can give you bad strings or possibly an exception.

String interpolation fixes this by letting you specify values in place within a string. To do this, you prefix the string with a dollar sign, then put your specific arguments in place:

string value = $"My name is {ob.Name}, and I was born in {ob.Birthday}";

You can even add formatting:

string value = $"My name is {ob.Name}, and I was born in 
    {ob.Birthday:yyyy}";

This will return the same value as the original string.Format example above. You can also add logic:

string value = $"My name is 
    {(!string.IsNullOrWhiteSpace(p.Name) ? p.Name : "Unknown")}, 
    and I was born in {ob.Birthday:yyyy}";

(You generally have to put parens around the logic to avoid confusing the parser).

This is a very cool feature, and I can see it being used when logging or building strings for internal use. The one place I probably won’t use it is in any place where I am building strings that are shown to the user–largely because I generally build localizable applications, so all of my user-visible strings will end up in resource files. There is no way to use string interpolation with resource files (which is probably a good thing, since otherwise localizers could really mess up your applications).

So I think this feature will be useful-ish, but somewhat limited.

Here are links to posts about other new features in C# 6.0:

Leave a Reply

Your email address will not be published. Required fields are marked *

*