Search code examples
c#stringstring-literalsstring-interpolationc#-11.0

Escape braces in C# interpolated raw string literal


I need braces in a raw string literal that uses interpolation:

var bar = "Bar";
var s = $"""
  Foo
  {bar}
  Baz
  {{Qux}}
""";
Console.WriteLine(s);

I expect the output to be "Foo\n Bar\n Baz\n {{Qux}}", but that won't compile:

The interpolated raw string literal does not start with enough '$' characters to allow this many consecutive opening braces as content CS9006

The docs linked above state:

Raw string literals can also be combined with interpolated strings to embed the { and } characters in the output string. You use multiple $ characters in an interpolated raw string literal to embed { and } characters in the output string without escaping them.

I tried ${${Qux$}$} and other combinations; none compile.

I can't find any examples. How is this done?


Solution

  • The leading $ and interpolation { and } must match in count.

    So to include verbatim substrings {{ and }} while also using interpolation, one must use $$$ with {{{ and }}}:

    var bar = "Bar";
    var s = $$$"""
      Foo
      {{{bar}}}
      Baz
      {{Qux}}
    """;