C# Tips

C# Tip Article

Escape curly brace in string.Format()

Sometimes I make mistakes not escaping curly brace in string formatting. For example, here is the code snippet which causes an exception.

// Wrong
var js = string.Format("function A() { alert('{0}') }", msg);

The code above will throw a FormatException as below:

[System.FormatException] = {System.FormatException: Input string was not in a correct format.
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, Para...

To fix the problem, we need to escape curly brace by using double braces ({{ and }}). Here is the fix.

// Correct   
var js = string.Format("function A() {{ alert('{0}') }}",msg);