C# 6.0 – String Interpolation

This is another post in the series on the new features that are coming in C# 6.0.

If you want to try out any of these features now, check out the Rosyln compiler and then install the Visual Studio 2015 Preview or fire up a VM in Azure with Visual Studio 2015 Preview already installed.

String interpolation in C# is fairly easy if you only have a couple of arguments, but it can be error prone with many arguments or if you need to re-order the arguments. It is also difficult to quickly see which variable gets substituted in where.

Currently, we write code like this,

var msg = string.Format("You ordered {0} {1}{{s}}", line.Quantity, line.Product.Name);

C# 6.0 makes this easier. You can omit the `String.format` and put the variables right in the curly braces. Notice the slash at the start.

var msg = "You ordered \{line.Quantity} \{line.Product.Name}{s}";

Notice that pesky improper pluralization though. It was always a pain to deal with. Now, just put the code you need inline.

var msg = "You ordered \{line.Quantity} \{line.Product.Name}\{line.Quantity > 1 ? "s" : ""}";

The syntax currently uses a slash before the brace. In a later update, it will be switching to a dollar sign before the first quote and no slash, like this,

var msg = $"You ordered {line.Quantity} {line.Product.Name}{s}";

If you want to check out the code for this series of posts, it is on GitHub at https://github.com/rprouse/CSharp60.