Apr 15, 2010

String.Format

Although very convenient for example for making templates and then replace with some values, it may cause tricky problems.

I've reached a code where it was used to add some data to a javascript.
So javascript uses a lot fo curly braces, which are at the same time used for string format to know where to put its values.

There is a way to escape those braces, buy double them, so for example :
function {}
will become
function {{}}

Recently I had the "String was not in a correct format." exception. I tried to debug and found nothing wrong with the string and the values that will be placed.
That was because I was expecting the values to be wrong (null references, something like this) and not the string itself.

Guess what did I discovered after a few minutes of debugging?
It was the string that was corrupted. The problem was that this particullar javascript was in the .ascx file. Someone probably hit the CTRL + K + D so the source was re-formatted, addding some white spaces in between the doubled curly braces.

Be warned that string.Format is kind of fragile when it comes to files that may involve curly braces.

No comments: