Updated on

To escape curly braces in C#, we double them: {{ gives us { and }} gives us }. The rule is the same in string.Format() and in interpolated strings, and raw string literals that start with $$ let us skip the doubling altogether.

Curly brackets mark placeholders in a format string, so a literal brace needs special treatment. We’ll also escape double quotes, backslashes and the other special characters a C# string can hold.

To download the source code for this article, you can visit our GitHub repository.

Let’s make a start.

What Do Curly Braces Mean in a C# Format String?

Formatted strings let us build output from fixed text and values. Curly braces mark the placeholders in these strings. Let’s consider a simple example of a formatted string:

var formattedString = string.Format("Hello, {0}!", name);

Here, {0} is a placeholder for the value of the name variable. string.Format() reads the format string when the code runs, and it treats every brace as the start or the end of a placeholder. So what happens when we want a brace in the output?

Don’t do this. A single brace in a format string isn’t treated as text:

var formatValue = "World";
var formattedString = string.Format("{Hello, {0}!}", formatValue);

The code compiles, but the call throws a FormatException when it runs:

Input string was not in a correct format. Failure to parse near offset 1. Expected an ASCII digit.

string.Format() saw { and expected a placeholder number right after it. The compiler can’t help here, because to the compiler the format string is just a string.

How Do We Escape Curly Braces in C#?

We double them. In a format string, {{ gives us one { and }} gives us one }. Interpolated strings follow the same rule, so $"{{Hello, {formatValue}!}}" produces {Hello, World!}.

In these strings, a single brace is never treated as text. string.Format() reads it as the start or end of a placeholder, and an unmatched one throws a FormatException at runtime. In an interpolated string, the compiler catches the same mistake and the build fails.

When the braces should wrap a value, we write three in a row. {{{0}}} is an escaped {{, the placeholder {0}, and an escaped }}. On .NET this also works with a format specifier, so {{{0:D5}}} prints a zero-padded number inside braces.

For text with lots of braces, like JSON, a raw string literal that starts with $$ saves us the doubling. We give it its own section below, with a JSON example.

To get a literal brace, we write it twice:

var formatValue = "World";
var formattedString = string.Format("{{Hello, {0}!}}", formatValue);

Here, the double curly brackets, {{ and }}, serve as escape sequences, so string.Format() reads them as literal braces rather than placeholders. The resulting string is {Hello, World!}. It’s a simple technique, and it works the same way in interpolated strings.

Escaping Curly Braces in Interpolated Strings

Let’s write the previous example with $:

var formatValue = "World";
var formattedString = $"{{Hello, {formatValue}!}}";

As you can see, the double braces become single braces in the output, and {formatValue} becomes the value:

{Hello, World!}

Unlike string.Format(), an interpolated string is checked when we build the code, so a stray closing brace stops the build with a clear message:

error CS8086: A '}' character must be escaped (by doubling) in an interpolated string.

We cover the rest of the $ syntax, alignment and format strings included, in our article on string interpolation.

Wrapping a Format Item in Curly Braces

Sometimes we want the braces around the value itself, for example to print an order number as {00042}. Here we need three braces on each side:

var orderNumber = 42;
var formattedString = string.Format("Order {{{0:D5}}}", orderNumber);

The first two opening braces are an escaped {, and {0:D5} is the placeholder with the D5 format, which pads the number to five digits. On the right, the first } closes the placeholder and the last two are an escaped }. The interpolated version reads the same way:

var orderNumber = 42;
var formattedString = $"Order {{{orderNumber:D5}}}";

Both return the same string:

Order {00042}

On .NET Framework, the same line gives a different result. Microsoft Learn’s composite formatting guide puts it this way: “Escaped braces with a format item are parsed differently between .NET and .NET Framework.” On .NET Framework, the }} right after D5 counts as an escaped brace and becomes part of the format string, so the number disappears and the line prints Order {D5}. Learn’s own {{{0:D}}} example prints {D} there. If we maintain .NET Framework code, the safe way is to pass the braces as arguments: string.Format("Order {0}{1:D5}{2}", "{", orderNumber, "}").

How Do Raw String Literals Change the Brace Rules?

Doubling every brace gets tiring fast when the text is JSON. C# 11 added raw string literals, and their interpolated form flips the rule around: instead of escaping the literal braces, we mark the placeholders.

A raw string literal starts and ends with at least three double quotes. When we put two $ signs in front, a placeholder needs two braces, and a single brace is just text:

var name = "John";
var age = 30;
var json = $$"""
    {
      "name": "{{name}}",
      "age": {{age}}
    }
    """;

Let’s check the output:

{
  "name": "John",
  "age": 30
}

The JSON reads exactly as it will come out. The quotes need no escaping either, and the indentation to the left of the closing """ is removed from every line.

The number of $ signs sets the rule. With $$, any run of one brace is text and two braces open or close a placeholder. If the text itself needs {{, we start with $$$ and use three braces for placeholders. The compiler stops us if we get it wrong. With a single $, the opening brace of our JSON would start a placeholder, and the build fails.

How Do We Escape Quotes, Backslashes and Other Special Characters?

Inside a regular string literal, the backslash starts an escape sequence. \" puts a double quote in the string, \\ puts a backslash, and sequences like \n, \t and \u00A9 add a new line, a tab or a Unicode character by its code.

Verbatim strings turn that off. With the @ prefix, a backslash is just a backslash, which is why Windows paths read better as @"C:\Program Files\". The one character that still needs care is the double quote, and we write it twice: @"She said ""hi""".

Raw string literals, added in C# 11, go one step further. Text between three double quotes needs no escaping at all, quotes and backslashes included.

Escape sequences and braces are separate rules. The compiler handles escape sequences, while braces only matter to format methods like string.Format() and to interpolation. A format string with quotes and braces needs both kinds of escaping: backslashes for the compiler and doubled braces for the format.

Double Quote

In a regular string, we put a backslash in front of the quote:

var message = "Important message"; 
var formattedString = string.Format("\"{0}\" is the message.", message);

The \" escape sequence puts a literal double quote into the string, so the result is "Important message" is the message.

A verbatim string writes the quote twice instead:

var message = "Important message";
var formattedString = string.Format(@"""{0}"" is the message.", message);

And a raw string literal needs no escaping at all:

var message = "Important message";
var formattedString = string.Format("""
    "{0}" is the message.
    """, message);

All three produce the same string. Notice that the raw version spans three lines. A single-line raw string can’t start with a quote character, so when the text begins with ", we use the multi-line form.

Backslash

Next, let’s tackle the task of escaping backslashes within a string:

var path = "C:\\Program Files\\";
var formattedString = string.Format("The installation path is: {0}", path);

The \\ escape sequence gives us one literal backslash, so the path doesn’t turn into unintended escape characters. The same path is easier to read as a verbatim string:

var path = @"C:\Program Files\";
var formattedString = string.Format("The installation path is: {0}", path);

Both versions return the same result:

The installation path is: C:\Program Files\

We look at more backslash cases, including regular expressions, in our article on escaping the backslash character.

Other Escape Sequences

Quotes and backslashes are the two we meet most, but C# has a short list of escape sequences for characters we can’t type directly:

Escape sequenceCharacterNotes
\'Single quoteNeeded in a char literal, optional in a string
\"Double quote
\\Backslash
\0Null
\aAlert
\bBackspace
\eEscape (U+001B)C# 13 and later
\fForm feed
\nNew line
\rCarriage return
\tHorizontal tab
\vVertical tab
\uHHHHUnicode character, four hex digits\u00A9 is ©
\U00HHHHHHUnicode character, eight hex digitsFor characters above U+FFFF, such as emoji
\xH to \xHHHHUnicode character, one to four hex digitsPrefer four digits: a hex digit right after it becomes part of the code

Be careful with \x. It takes as many hex digits as it finds, up to four, so "\xA1A" is one character, not ¡ followed by A. Writing all four digits avoids the surprise. Line breaks have their own pitfalls across operating systems, which we cover in our article on replacing line breaks.

Conclusion

We’ve learned that a curly brace in a format string is a placeholder unless we double it, and that the rule holds in string.Format() and in interpolated strings alike. Three braces wrap a value in literal braces, and on .NET that works with a format specifier too.

For brace-heavy text like JSON, a raw string literal with $$ turns the rule around, so the text stays readable. Double quotes and backslashes are a separate layer: we escape them with a backslash, or switch to a verbatim or raw string.

Tested with .NET 10.0.10 and MSTest 4.5.2.