Tuesday, April 20, 2010

Escaping braces when using string.Format() to output a literal brace

Typically a backslash will be used to escape characters in a C# string. However, with the string.Format() method you double up the braces ("{{", "}}") to produce a literal.

E.g. The following will result in a FormatException.

string.Format("function JavaScriptFunction() { return {0}; }", variableToReturn);

Escaping the required braces to output literals produces the correct output.

string.Format("function JavaScriptFunction() {{ return {0}; }}", variableToReturn);

From MSDN:

To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}".