Saturday, September 27, 2008

string format gotcha

here's a simple, inoffensive looking piece of code:

...
LogError(string.Format("some message, some variable value {0}" + ex.Message, varValue));
...

Can you spot the problem with this code?

4 comments:

Anonymous said...

ex.Message can contain brackets that could lead to a FormatException thrown by String.Format. Is that what you're looking for?

BlackTigerX said...

yep, just found some code that was doing that, it seems innocent but can definitely cause problems in production

Anonymous said...

I believe these are our alternatives:

LogError(string.Format("some message, some variable value {0}", varValue) + ex.Message);

LogError(string.Format("some message, some variable value {0}{1}", varValue, ex.Message));

BlackTigerX said...

yep, whichever way you prefer