String interpolation in C# 6

This is the eighth part of a series of posts I’m making into Upcoming Language Feature Changes in C# 6. (Now Visual Studio 2015 is available, they’re not so “upcoming”).

This is another really nice piece of syntactic sugar that makes the code more readable and less error prone. Very simply, this appears to be designed to overcome some of the shortcomings of String.Format and its related uses.

Basic usage

In the most basic form, rather than specifying {0}, {1} etc throughout your string, simply prefix the string with $ and you can place the expression you want formatted directly in the string:

// before String interpolation
var output = String.Format("Car {0} is {1} year(s) old", myCar.Registration, myCar.Age);

// String interpolation it becomes
var output6 = $"Car {myCar.Registration} is {myCar.Age} year(s) old";

This is not only easier to read, but will make future maintenance easier. You will no longer have to put the right number in between the curly brackets and count the parameters.

Advanced Usage

A really nice thing about string interpolation is that you’re not limited to just variables, you can in put virtually any expression, for example:

Console.WriteLine($"Car {myCar.Registration} is {myCar.Age} year{ (myCar.Age == 1 ? "" : "s")} old");


All in all, another great tweak to the language which should help the Developer Experience (DX) – something I saw in the ReactEurope conference.

Leave a Reply

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