Using curly braces in a C# String.Format format pattern

Thoughts from the team
By    | January 15, 2011 | Code Snippets,

This is a gotcha which caught me out and after banging my head against my desk to 10 minutes was easily solved by reading the documentation.  I was trying to use StringBuilder.AppendFormat to build up a JavaScript function and kept getting hit with a FormatException when trying to do this:

sb.AppendFormat("function {0}(args) { return false; }", someVariable);

The problem, of course, is that you can’t use the characters { or } inside a format string for String.Format() as they are special characters used to identify variables, as I have done in the example with the use of {0}.

The solution is actually fairly straightforward but not immediately obvious.  My first thought was to escape the special characters using the standard “\” , for example:

sb.AppendFormat("function {0}(args) \{ return false; \}", someVariable);

But that code generated the same FormatException.  After a little while I gave up and read the documentation (remember kids, always RTFM!) for the answer.  The code I wanted was:

sb.AppendFormat("function {0}(args) {{ return false; }}", someVariable);

Instead of using “\” as an escape character, you double up the special characters {{ or }}.  Easy.  When you know how.
Life is too short for man pages, but occasionally much too short without them.

More like this