Include literal braces in C# format strings

Composite formatting treats braces as the boundaries of a placeholder. Double each brace that should appear literally in the output.

For structured text, modern raw interpolated strings offer another readable spelling. These examples produce a small display string. Use a JSON serializer for real JSON values that require escaping.

Compare the two forms

In a .NET console project's Program.cs, run:

C#
using System.Globalization;

var count = 3;
var composite = string.Format(CultureInfo.InvariantCulture,
	"{{\"count\":{0}}}", count);
var raw = $$"""{"count":{{count}}}""";

Console.WriteLine(composite);
Console.WriteLine(raw);

Both lines print {"count":3}. In the composite string, {{ and }} emit literal braces while {0} supplies the argument. In the raw string, two dollar signs mean that a pair of braces introduces an interpolation, leaving single braces literal.

Choose the boundary carefully

Only escape braces when text passes through a formatting parser. A plain string containing { does not need doubling. Avoid composing format strings from uncontrolled text because a stray opening brace or an out-of-range placeholder can throw FormatException.

For actual JSON, System.Text.Json.JsonSerializer.Serialize(new { count }) handles strings, escaping and numeric serialization together. Formatting syntax should not become a substitute for the output format's serializer.

Official references

Composite formatting - .NET
Learn about .NET composite formatting, which takes as input a list of objects and a composite format string, containing fixed text with indexed placeholders.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting
Composite formatting
$ - string interpolation - format string output - C# reference
String interpolation using the `$` token provides a more readable and convenient syntax to format string output than traditional string composite formatting.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Interpolated strings

Author: Herman Schoenfeld