[c#] How to escape braces (curly brackets) in a format string in .NET

How can brackets be escaped in using string.Format.

For example:

String val = "1,2,3"
String.Format(" foo {{0}}", val); 

This example doesn't throw an exception, but outputs the string foo {0}.

Is there a way to escape the brackets?

This question is related to c# .net string parsing formatting

The answer is


Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format parsing.

Escaping Brackets: String Interpolation $("") and String.Format

string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");

// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>

Escaping Brackets: String Interpolation $("") :

Now, you can also use c# string interpolation like this (feature available in C# 6.0)

var inVal= "1, 2, 3";
var outVal= $" foo {{{inVal}}}";
//Output will be:  foo {1, 2, 3}

or you can use c# string interpolation like this (feature available in C# 6.0)

var value = "1, 2, 3";
var output = $" foo {{{value}}}";

Came here in search of how to build json strings ad-hoc (without serializing a class/object) in C#. In other words, how to escape braces and quotes while using Interpolated Strings in C# and "verbatim string literals" (double quoted strings with '@' prefix), like...

var json = $@"{{""name"":""{name}""}}";

Yes to output { in string.Format you have to escape it like this {{

So this

String val = "1,2,3";
String.Format(" foo {{{0}}}", val);

will output "foo {1,2,3}".

BUT you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}

int i = 24;
string str = String.Format("{{{0:N}}}", i); //gives '{N}' instead of {24.00}

But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case you have to use this instead.

String.Format("{0}{1:N}{2}", "{", i, "}") //evaluates to {24.00}

Reference Articles String.Format gottach and String Formatting FAQ


Came here in search of how to build json strings ad-hoc (without serializing a class/object) in C#. In other words, how to escape braces and quotes while using Interpolated Strings in C# and "verbatim string literals" (double quoted strings with '@' prefix), like...

var json = $@"{{""name"":""{name}""}}";

Escaping Brackets: String Interpolation $("") :

Now, you can also use c# string interpolation like this (feature available in C# 6.0)

var inVal= "1, 2, 3";
var outVal= $" foo {{{inVal}}}";
//Output will be:  foo {1, 2, 3}

Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

or you can use c# string interpolation like this (feature available in C# 6.0)

var value = "1, 2, 3";
var output = $" foo {{{value}}}";

You can use double open brackets and double closing brackets which will only show one bracket on your page.


My objective:

I needed to assign the value "{CR}{LF}" to a string variable delimiter.

Code c#:

string delimiter= "{{CR}}{{LF}}";

Note: To escape special characters normally you have to use . For opening curly bracket {, use one extra like {{. For closing curly bracket }, use one extra }}.


Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

[TestMethod]
public void BraceEscapingTest()
{
    var result = String.Format("Foo {{0}}", "1,2,3");  //"1,2,3" is not parsed
    Assert.AreEqual("Foo {0}", result);

    result = String.Format("Foo {{{0}}}", "1,2,3");
    Assert.AreEqual("Foo {1,2,3}", result);

    result = String.Format("Foo {0} {{bar}}", "1,2,3");
    Assert.AreEqual("Foo 1,2,3 {bar}", result);

    result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
    Assert.AreEqual("{N}", result);

    result = String.Format("{0}{1:N}{2}", "{", 24, "}");
    Assert.AreEqual("{24.00}", result);

    result = String.Format("{{{0}}}", 24.ToString("N"));
    Assert.AreEqual("{24.00}", result);
}

[TestMethod]
public void BraceEscapingTest()
{
    var result = String.Format("Foo {{0}}", "1,2,3");  //"1,2,3" is not parsed
    Assert.AreEqual("Foo {0}", result);

    result = String.Format("Foo {{{0}}}", "1,2,3");
    Assert.AreEqual("Foo {1,2,3}", result);

    result = String.Format("Foo {0} {{bar}}", "1,2,3");
    Assert.AreEqual("Foo 1,2,3 {bar}", result);

    result = String.Format("{{{0:N}}}", 24); //24 is not parsed, see @Guru Kara answer
    Assert.AreEqual("{N}", result);

    result = String.Format("{0}{1:N}{2}", "{", 24, "}");
    Assert.AreEqual("{24.00}", result);

    result = String.Format("{{{0}}}", 24.ToString("N"));
    Assert.AreEqual("{24.00}", result);
}

My objective:

I needed to assign the value "{CR}{LF}" to a string variable delimiter.

Code c#:

string delimiter= "{{CR}}{{LF}}";

Note: To escape special characters normally you have to use . For opening curly bracket {, use one extra like {{. For closing curly bracket }, use one extra }}.


You can use double open brackets and double closing brackets which will only show one bracket on your page.


Almost there! The escape sequence for a brace is {{ or }} so for your example you would use:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format parsing.

Escaping Brackets: String Interpolation $("") and String.Format

string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");

// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r