Coder Perfect

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

Problem

When using string.Format, how may brackets be escaped?

For example:

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

Although this example does not cause an error, it does print the string foo 0.

Is it possible to get rid of the brackets?

Asked by Pop Catalin

Solution #1

To produce foo 1, 2, 3, you must do something like this:

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

To output a and to output a, you must utilize both.

Alternatively, you may now utilize C# string interpolation, which is supported in C# 6.0.

String interpolation $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (“”). In C# 6.0, it’s a brand-new feature.

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

Answered by Jorge Ferreira

Solution #2

Yes, in order to output as a string. You must escape it in the following format:

As a result, the output will be “foo 1,2,3.”

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

However, you should be aware of a design flaw in C#, which is that based on the above logic, you would expect the following code to display 24.00:

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

This, on the other hand, prints N. Because of the way C# parses escape sequences and format characters, this is the case. In the above example, you must instead use this to obtain the desired value:

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

Answered by Guru Kara

Solution #3

We’re almost there! For your case, the escape sequence for a brace is or, therefore you’d use:

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

Answered by Wolfwyrd

Solution #4

You can use double open and double closed brackets to have your page just show one bracket.

Answered by elec

Solution #5

Getting rid of curly brackets while also employing string interpolation is a fun challenge. To avoid string interpolation and string.format parsing, you must use quadruple brackets.

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>

Answered by SliverNinja – MSFT

Post is based on https://stackoverflow.com/questions/91362/how-to-escape-braces-curly-brackets-in-a-format-string-in-net