Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 983
lonix Avatar asked Dec 04 '25 09:12

lonix


1 Answers

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}}
""";
like image 121
lonix Avatar answered Dec 05 '25 22:12

lonix