Escaping {{Braces}} For String.Format

153 words.

Amazingly enough, I hadn’t run across this situation before.  I was writing a quick utility to generate a C# class from a database table today, and I discovered that the following code failed:

Console.WriteLine( "get { return {0}; }", privatePropertyName );

The string formatter was attempting to parse all of the braces, and it obviously didn’t understand what to do with the first and last one.  Doh!  Hadn’t seen that one before.  But no problem, I thought.  I’ll just draw upon my vast experience and escape them with backslashes, like this:

Console.WriteLine( "get \{ return {0}; \}", privatePropertyName );

Bzzt.  Wrong.  Some hunting on MSDN revealed that you actually need to escape braces in .NET formatted strings by using {{ and }}.  It was definitely a forehead-smacking moment.

Console.WriteLine( "get {{ return {0}; }}", privatePropertyName );

P.S.  Interestingly, the following works as expected:

Console.WriteLine( "get { return 0; }" );

Live and learn.

Related

This page is a static archival copy of what was originally a WordPress post. It was converted from HTML to Markdown format before being built by Hugo. There may be formatting problems that I haven't addressed yet. There may be problems with missing or mangled images that I haven't fixed yet. There may have been comments on the original post, which I have archived, but I haven't quite worked out how to show them on the new site.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.