Tuesday, June 5, 2012

How to escape brackets in a format string in .Net


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.


Source: Tips4all

3 comments:

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

    ReplyDelete
  2. 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);

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

    ReplyDelete