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

Pop Catalin picture Pop Catalin · Sep 18, 2008 · Viewed 296.1k times · Source

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?

Answer

Jorge Ferreira picture Jorge Ferreira · Sep 18, 2008

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