When a C# code generator embeds JSON with interpolated values in a raw string literal, why use $$""" and how many braces open a hole?
answer
- JSON is mostly braces
- count the dollar signs
- shorter runs are plain text
- innermost braces form the hole
basics
~20 sThe count of $ signs sets how many braces delimit a hole: under $$, {{expr}} is a hole and single braces are text, so JSON needs no escaping. Doubling braces does not escape them in raw literals (CS9006).
solid answer
~40 sIn an interpolated raw literal, a run of braces shorter than the number of `$` signs is content, and exactly that many braces open and close a hole. With one `$`, the JSON's own `{` opens a hole and the code stops compiling, so JSON templates use `$$"""` and write values as `{{invoiceId}}` or `{{total:F2}}`. Text that already contains `{{ }}` needs `$$$`. Longer runs group from the inside: `$$"""{{{id}}}"""` prints `{7}`. The regular-string habit of doubling braces does not work here; the SDK reports CS9006 and asks for more `$` signs. Two things raw interpolation leaves to you: values are not JSON-escaped, and numbers still use the current culture.
code
csharp · 20 linesusing System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string invoiceId = "INV-1001";
decimal total = 1234.5m;
string json = $$"""
{
"invoiceId": "{{invoiceId}}",
"total": {{total:F2}},
"tags": {}
}
""";
Console.WriteLine(json);
// Three braces with $$: the outer pair is content, the inner pair is the hole
Console.WriteLine($$"""Template token: {{{invoiceId}}}""");
// Three dollars: {{ }} is now literal text, {{{ }}} opens a hole
Console.WriteLine($$$"""Placeholder: {{name}} for {{{invoiceId}}}""");go deeper
Recall that raw literals can be interpolated and that the number of dollar signs matters for braces.
Explain the rule: brace runs shorter than the dollar count are text, and a hole uses exactly that many braces.
Build a JSON or source-code template with $$, predict the output for longer brace runs, and remember that values are neither escaped nor culture-neutral.
Judge when string templates in a generator should give way to a serializer or a syntax-tree builder, because hand-built JSON and C# drift once values get messy.
"## The problem: JSON is made of braces A code generator that writes C# test files often embeds expected JSON with a few values filled in. In a regular interpolated string every literal brace must be doubled (`{{` and `}}`), and every quote escaped, so the fixture stops looking like JSON. A plain `$"""` raw literal (one dollar sign) fixes the quotes but not the braces: with one `$`, **every single `{` opens a hole**. The JSON's opening brace becomes the start of an expression, and the SDK answers with errors such as CS1056, "Unexpected character '{'", at a brace further on. ## The rule: count the dollar signs C# 11 lets an interpolated raw literal start with **more than one `$`**. The count sets the brace grammar: | Prefix | Braces that are plain text | Braces that delimit a hole | |---|---|---| | `$"""` | none | `{expr}` | | `$$"""` | runs of 1: `{`, `}` | `{{expr}}` | | `$$$"""` | runs of 1 or 2: `{{`, `}}` | `{{{expr}}}` | In words: a run of braces **shorter** than the number of `$` signs is content, and a hole is opened and closed by **exactly as many** braces as there are `$` signs. Pick the count as one more than the longest brace run in the content: `$$` for JSON, `$$$` for text that already contains `{{ }}` placeholders, such as a text template that already uses `{{name}}` placeholders. ## A worked example ```csharp string json = $$""" { "invoiceId": "{{invoiceId}}", "total": {{total:F2}}, "tags": {} } """; ``` - The outer `{`, `}` and the empty `{}` are single braces, so they are text. - `{{invoiceId}}` and `{{total:F2}}` are holes. Width and format specifiers work as usual inside them. - The multi-line raw rules still apply: the indentation left of the closing `"""` is stripped. ## Longer runs group from the inside out When a run of braces is longer than the hole delimiter, the innermost braces form the hole and the extra outer ones are text: 1. `$$"""{{{id}}}"""` prints `{7}` when `id` is 7: the inner pair is the hole, the outer single braces are content. 2. `$$"""{"id": {{id}}}"""` prints `{"id": 7}`: `}}}` closes the hole with two braces and leaves one closing brace as text. 3. `$$$"""Placeholder: {{name}} for {{{id}}}"""` keeps `{{name}}` as literal text and fills only the triple-brace hole. ## Errors you will meet - **Doubling does not escape in a raw literal.** `$"""{{"id": {id}}}"""` is not the regular-string escape; the SDK reports **CS9006**, "The interpolated raw string literal does not start with enough '$' characters to allow this many consecutive opening braces as content." Add a `$` instead. - The same CS9006 appears when a run of opening braces is longer than a hole plus the allowed content, for example `$$"""{{{{id}}}}"""`. - With a single `$`, JSON braces open holes and produce syntax errors such as CS1056. ## Choosing the dollar count, step by step 1. Find the longest run of literal braces the output must contain: `1` for JSON, `2` for a `{{ }}` template. 2. Use one more `$` than that run. 3. Wrap each value in exactly that many braces, adding a width or format after a comma or colon as usual. 4. Read the generated output once in a test: brace grouping is easy to predict but also easy to misjudge by one. ## What raw interpolation does not do - **It does not escape values.** An interpolated string containing `"` or `\` is inserted as is and can break the JSON. Serialize or escape values that may contain such characters. - **It does not change the culture.** `{{total:F2}}` still formats with the current culture, so a de-DE machine writes `1234,50`, which is not a JSON number. Generate under `CultureInfo.InvariantCulture`, or wrap the literal in `string.Create(CultureInfo.InvariantCulture, $$"""...""")`. - **It is purely a compile-time feature.** The result is an ordinary string built the same way as any other interpolated string.
- Can you escape a literal brace by doubling it in a $""" raw literal, as you would in a regular $"" string?No. In raw interpolation, brace runs are counted against the number of `$` signs, so `{{` with one `$` asks for more content braces than allowed and the SDK reports CS9006. The fix is another `$`: with `$$`, a single brace is text and `{{expr}}` is the hole.
- Does interpolating a string into a $$ JSON template always produce valid JSON?No. The value is inserted verbatim: a customer name containing a double quote or a backslash breaks the document, and the literal does no JSON escaping. Serialize such values, or escape them, before they reach the hole. Numbers need the invariant culture for the same reason.
- Why does {{total:F2}} write 1234,50 into the JSON on some build machines?A raw interpolated literal formats holes like any interpolated string, with `CultureInfo.CurrentCulture`, and de-DE uses a comma as the decimal separator. Run the generator under the invariant culture or pass it explicitly with `string.Create(CultureInfo.InvariantCulture, $$"""...""")`.
- In a raw interpolated literal, {{ escapes a brace just as in a regular $"" string.
- $$ means the string is interpolated twice.
- Under $$, a single brace must still be doubled to appear in the output.
- Raw interpolation escapes inserted values so the JSON stays valid.
- The number of $ signs must match the number of quotes in the delimiter.