Skip to content

String interpolation C# 6.0code reductionreadability

Build formatted strings with in-place evaluation.

Strings are often built upon from a number of elements. Prior to C# 6.0 the most popular options were either to append a number of items together or to use String.Format (and in cases of building very large strings StringBuilder).

C# 6.0 offers a interpolated strings allowing a special $-prefixed string to contain expressions within { and } separators. Think of it as a String.Format where instead of the {0} placeholders the expressions are inline (and therefore easier to read).

Code

C#
var output = $"The result is {(a+b)/c} for average of {values.Average():g}";
C#
var output = "The result is " (a+b)/c + " for average of " + values.Average().ToString("g");
C#
var output = String.Format("The result is {0} for average of {1:g}", (a+b)/c, values.Average());

Notes

  • Consider String.Format if you supporting multiple languages as the format string can be localized
  • Be aware that String.Format has additional runtime overhead so avoid it in hot paths
  • You can also use verbatim interpolated strings (ones where \ has no special escape-code meaning) using the $@ prefix, e.g. $@"The unicode is \u{codepoint:x4}"
  • Do not confuse with the similar-sounding but quite different string interning

More information