1168

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pop Catalin
  • 61,751
  • 23
  • 87
  • 115
  • 2
    MSDN String Formatting FAQ http://msdn.microsoft.com/en-us/netframework/aa569608: How do I write out a curly bracket in string formats? Do escaped curly brackets have any odd behaviors I need to be aware of? How can I use string formatting to write out something like "{42.00}"? – gerryLowry Nov 05 '11 at 09:30
  • 3
    Unfortunately, the above MSDN link is broken. Currently, the correct link seems to be https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx (seet the QA section at the bottom, or search for "escape" on the page). – Palo Mraz Apr 14 '17 at 05:21
  • Came here when looking for a double curly brackets in a raw string. The solution: if you need 2 curly brackets in a string, you have to use 3 dollars, example: $$$"""\n{ "key": "{{value}}" }\n""", meaning that for a variable you would use 3 curly brackets (e.g. {{{variable}}}) . If you need 3 curly brackets in a string, use 4 dollars. – xhafan Apr 28 '23 at 13:28

12 Answers12

1471

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}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jorge Ferreira
  • 96,051
  • 25
  • 122
  • 132
  • 138
    "{{" is treated as the escaped bracket character in a format string. – icelava Sep 18 '08 at 10:18
  • 6
    But if you want to add value formatting to your string specifier you need also to read the answer from Guru Kara below. – Nick Mar 01 '13 at 17:24
  • 2
    Read the section _Escaping Braces_ in the official documentation [_Composite Formatting_](http://msdn.microsoft.com/en-us/library/txafckwd.aspx). – Jeppe Stig Nielsen Apr 07 '13 at 09:32
  • 11
    It's also working in new C# 6 string interpolation (`$"a = {{ {a} }}"`) – Mahmood Dehghan Apr 03 '16 at 05:55
  • More specific on the C# 6 string interpolation way, doubling up on the curly works like so `string v = $" foo {{{t}}}";`. If you has other characters to escape that's not a curly you can use the $@ combo `string v2 = $@"\foo {{{t}}}\";` – Nhan Apr 14 '16 at 22:04
230

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Guru Kara
  • 6,272
  • 3
  • 39
  • 50
  • 14
    If I ran into that bug, I'd write `string.Format( "{{{0}}}", i.ToString("N") );` which may be more readable to some. – HappyNomad May 08 '14 at 03:25
  • 2
    @Happy It might, but you'd then find yourself specifying the FormatProvider twice, with the risk that you'd specify different ones, or miss one. – ClickRick Apr 20 '15 at 09:02
80

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);
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
Wolfwyrd
  • 15,716
  • 5
  • 47
  • 67
25

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

Ryan Berger
  • 9,644
  • 6
  • 44
  • 56
elec
  • 251
  • 3
  • 2
17

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}""}}";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adam Cox
  • 3,341
  • 1
  • 36
  • 46
16

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>
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
7
[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);
}
pomber
  • 23,132
  • 10
  • 81
  • 94
4

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

var value = "1, 2, 3";
var output = $" foo {{{value}}}";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aarif
  • 1,595
  • 3
  • 17
  • 29
4

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Goldfish
  • 624
  • 6
  • 11
2

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

Mohamed Anas
  • 194
  • 2
  • 7
0

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}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 3
    This seems to be a plagiarised version of [Jorge Ferreira's answer](https://stackoverflow.com/questions/91362/how-to-escape-braces-curly-brackets-in-a-format-string-in-net/91375#91375) and/or [Aarif's answer](https://stackoverflow.com/questions/91362/how-to-escape-braces-curly-brackets-in-a-format-string-in-net/48081666#48081666) (incl. the spelling mistakes) (original revisions). – Peter Mortensen Jun 14 '21 at 00:04
0

I wanted to escape {{Id}} while I'm in a string interpolation

This worked for me:

string url = $"/Details/{{{{Id}}}}";

output:

/Details/{{Id}}
Adel Mourad
  • 1,351
  • 16
  • 13