I saw this recently over an internal email list and I thought I’d share it… 

A developer asks:

I’ve found a bug in the way String.Format handles close curly literals.  It’s provoked by having a format specifier on a string.  The attached code demonstrates this on .NET Framework 1.1.  The core of it goes as follows:

// BUG: "}}" to get a literal "}" doesn't work
// when ":d" (or other) format specifier is present:

string wrong = String.Format("{{{0:d}}}", 42);

Here I’d expect the produced string to be “{42}”, but instead I get “{d}”.  I first ran into this bug using the :x (hex) format specifier, so I expect others are also implicated.

Kit George, the PM for this feature responds:

 

This actually isn’t a bug.

Consider this example:

 

string right1=String.Format("{0:d!}", 42);

 

We know that’s the wrong format specifier in the middle there (d!), but if we Console.WriteLine the result, we get:

 

d!

 

Going a step further:

 

string right3=String.Format("{{{0:d!}}}", 42);           

 

produces

{d!}

 

So the first thing we know is, if you put in  a string for the specifier that is longer than one character, string.format simply prints that literal out.

 

The reason you’re item comes out the way it does, is because we resolve the escaped curly brackets in the order we’re given them. Therefore:

 

{{      is escaped

{0:d looks like formatting

}}       is escaped

}        ends the formatting section

 

Therefore, the formatting routine thinks that what’s in the formatting section is in fact:

 

0:d}

 

It therefore simply prints out d} as a literal, just like it prints out d!, if that’s what we had given it.

 

However, I have made sure the docs for this area get cleaned up to make this more clear.