How to escape braces (curly brackets) in a format string in .NET

C#.NetStringParsingFormatting

C# Problem Overview


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 it outputs the string foo {0}.

Is there a way to escape the brackets?

C# Solutions


Solution 1 - C#

For you to output foo {1, 2, 3} you have to do something like:

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

To output a { you use {{ and to output a } you use }}.

Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)

Escaping brackets: String interpolation $(""). It is new feature in C# 6.0.

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

Solution 2 - C#

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

So the following will output "foo {1,2,3}".

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

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

Solution 3 - C#

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);

Solution 4 - C#

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

Solution 5 - C#

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>

Solution 6 - C#

I 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}""}}";

Solution 7 - C#

[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);
}

Solution 8 - C#

Or you can use C# string interpolation like this (feature available in C# 6.0):

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

Solution 9 - C#

My objective:

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

C# code:

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, }}.

Solution 10 - C#

You can also use like this. var outVal = $" foo {"{"}{inVal}{"}"} --- {"{"}Also Like This{"}"}"

Solution 11 - C#

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}}}";
// The output will be:  foo {1, 2, 3}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPop CatalinView Question on Stackoverflow
Solution 1 - C#Jorge FerreiraView Answer on Stackoverflow
Solution 2 - C#Guru KaraView Answer on Stackoverflow
Solution 3 - C#WolfwyrdView Answer on Stackoverflow
Solution 4 - C#elecView Answer on Stackoverflow
Solution 5 - C#SliverNinja - MSFTView Answer on Stackoverflow
Solution 6 - C#Adam CoxView Answer on Stackoverflow
Solution 7 - C#pomberView Answer on Stackoverflow
Solution 8 - C#AarifView Answer on Stackoverflow
Solution 9 - C#GoldfishView Answer on Stackoverflow
Solution 10 - C#Mohamed AnasView Answer on Stackoverflow
Solution 11 - C#Manish Kumar GurjarView Answer on Stackoverflow