Vegard Andreas Larsen Vegard Andreas Larsen, slightly peeking above the bottom edge.

String interpolation with C# 6.0

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:

var place = "world";
Debug.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.

var place = "world";
var formattable = (FormattableString)$"Hello {place}!";
var 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):

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


Published 2017-08-15. Last updated 2022-12-19.