I'm really quite surprised that I've never needed this before, but today I wanted to embed some JavaScript within a string contained in a C# class and format it using string.Format().

The problem? My JavaScript was a function declaration and therefore contained braces, but the placeholder delimiters in string.Format also use braces.

The solution: braces get escaped using another brace of the same sort.

var jsConditionalHelloWorldTemplate =
    "if ({0}) {{\r\n" +
    "    alert('Hello, world!');" +
    "}}" +
    "";

var sendToBrowser = string.Format(jsConditionalHelloWorldTemplate, "true");
writer.Write(sendToBrowser);

How did I not know this before?