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.
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.