String interpolation with C# 6.0

Vegard Andreas Larsen

One of the highly anticipated features in C# 6.0 was string interpolation, which meant you could rewrite all of your ugly String.Format calls into a more natural syntax:

1var place = "world";
2Debug.WriteLine($"Hello {place}!");

While this by itself is incredibly useful, there is more lurking beneath the surface of this feature than I imagined.

I found a hint of it in the release notes for Entity Framework Core 2.0, under the headline “String interpolation in raw SQL methods”.

It allows you to use C# 6.0 string interpolation to safely insert parameters into a SQL string. To do this, they rely on the fact that by casting a string interpolation expression to FormattableString at the time of creation, you can access the format string and arguments afterwards. If you don’t immediately coerce the variable into a FormattableString, it magically turns into a regualar string.

1var place = "world";
2var formattable = (FormattableString)$"Hello {place}!";
3var output = string.Format(formattable.Format, "universe"); // "Hello universe!"

The FormattableString class won’t let you change the generated string directly, and ToString will yield the same string you would have started with. But the generated format string itself fits neatly into string.Format, so you can easily generate a new string with the same parameters (or slightly modify them if you’d like):

1var place = "world";
2var formattable = (FormattableString)"Hello {place}!";
3var output = string.Format(formattable.Format, formattable.GetArguments());