views:

6819

answers:

4

How can brackets be escaped in a C# format string so, something like :

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

doesn't throw a parse exception but actually outputs the string " foo {1,2,3}"

Is there a way to escape the brackets or should a workaround be used.

+36  A: 

Actually your example outputs: foo {0}

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 put a { you use {{ and to put a } you use }}.

smink
It doesn't output "foo {0}" because the parser tries to find parameter 0, doesn't find it and throws an parse exception. but it it would find {0} somewhere else int the string "{{0}}" would be output as "{0}".And thank your for your answer.
Pop Catalin
"{{" is treated as the escaped bracket character in a format string.
icelava
+7  A: 

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);
Wolfwyrd
A: 

Doblue open brackets and double closing brackets you can use. But only visible one bracket on your page.

elec
A: 

Here is a more generic and far lazier solution to solve your problem:

public static string FormatWithBrackets(this string strObj, params object[] formatParameters)
{
    //  Duplicate the brackets to enable formatting syntax
    var tempStr = strObj.Replace("{", "{{").Replace("}", "}}");

    //  Remove double brackets from formatting arguments
    tempStr = Regex.Replace(tempStr, @"{{(\d+)}}", @"{$1}");

    //  Usual formatting (will also remove the rest of the double brackets)
    return string.Format(tempStr, formatParameters);
}

Of course, this is not performance smart, but it'll fit your need unless you code a Real Time application.

Enjoy.

Eran Betzalel
This is ridiculous. See the accepted answer.
JD
I should have been more clear and say that this solution fits a formatting problem where you cannot represent a bracket by double brackets, for example, HTML template.
Eran Betzalel