C# 6 Preview: String Interpolation

Update 31st January 2015: The syntax for string interpolation has changed as from VS2015 CTP5, as per the example at the end of this article. Please see C# 6 Preview: Changes in VS2015 CTP 5 for the latest syntax and examples. This article remains available due to historical significance.

Visual Studio 2015 Preview was released last week, and it supercedes the CTPs of what was previously known as “Visual Studio 14”. This VS2015 pre-release comes with a new C# 6.0 feature that wasn’t in the CTPs: string interpolation. Let’s learn about this feature by looking at an example.

I’ve got this Customer class with properties for an Id (integer), FirstName, LastName, and DateOfBirth, and I’ve declared an instance as follows:

            var dateOfBirth = new DateTime(2014, 10, 12);
            var customer = new Customer(1354, "Tony", "Smith", dateOfBirth);

Now, if I want to combine the first and last names into a full name, I can use the typical string.Format():

            var fullName = string.Format("{0} {1}", customer.FirstName, customer.LastName);

But in C# 6.0, I can use string interpolation to take out the placeholders and incorporate the string formatting arguments (in this case the two properties) directly in the string:

            var fullName = "\{customer.FirstName} \{customer.LastName}";

This eliminates the need to have placeholders that match the arguments, which can be a nightmare to maintain when you have a lot of them.

Just like string.Format(), string interpolation allows you to include formatting arguments:

            var dob2 = "Customer \{customer.IdNo} was born: \{customer.DateOfBirth:"yyyy-MM-dd"}";

In the case of the date, I had to put the format string in quotes to prevent the dashes from being interpreted as minus signs.

VS2015 highlights interpolated strings such that the referenced variables are shown as such, and not as part of the string:

vs2015-string-interpolation-highlighting

The actual syntax of string interpolation is going to change. String interpolation has gone through numerous discussions (such as this, this and this), and the development team has decided to change it for the benefit of the language. Quoting the latest C# feature descriptions (PDF):

“Note: This describes the syntax that works in the Preview. However, we’ve 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";