Escape curly brace '{' in String.Format
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In C# composite formatting, curly braces are special characters because they mark format items such as {0} and {1}. If you want a literal brace in the output of String.Format, you must escape it by doubling it.
The Basic Rule
Use:
- '
{{for a literal opening brace' - '
}}for a literal closing brace'
Example:
Output:
That doubling rule is the core answer to the question.
Mixing Literal Braces with Placeholders
You can combine escaped braces and normal placeholders in the same format string.
Output:
The formatter treats {0} and {1} as replacement fields, while doubled braces become literal characters.
Why a Single Brace Fails
This is invalid:
And this is also invalid:
The formatter expects braces to be part of a valid formatting structure. A single unmatched brace causes a FormatException.
That exception is often the first clue that a supposedly literal brace was parsed as formatting syntax instead.
A More Realistic Example
Literal braces are common when generating text that resembles JSON, templates, or configuration fragments.
Output:
This works because the outer braces are escaped, while the placeholders remain normal composite-format items.
String.Format Versus String Interpolation
Modern C# often uses string interpolation instead of String.Format:
But even with interpolation, literal braces still need escaping:
So the “double the brace” rule is useful beyond String.Format itself.
Reading Composite Format Strings Carefully
Complex format strings can become hard to read when they mix:
- placeholders
- alignment specifiers
- numeric or date formats
- escaped braces
For example:
Output:
Once the string becomes too dense, consider breaking it into smaller pieces or switching to a clearer construction style.
Common Pitfalls
The most common mistake is escaping only one side of the brace pair. Both literal opening and closing braces must be doubled.
Another issue is forgetting that interpolation also uses braces for expressions. Developers sometimes move from String.Format to interpolation and assume brace escaping rules disappear. They do not.
A third pitfall is building JSON-like text manually with formatted strings when a serializer would be safer. Escaping braces solves the syntax problem, but serializers are usually better for real structured output.
Summary
- In
String.Format, use{{and}}for literal braces. - Single unmatched braces cause formatting errors.
- Escaped braces can be mixed with normal placeholders such as
{0}. - The same doubling rule also matters in string interpolation.
- For complex structured output, consider serializers instead of manual string formatting.

