2008-12-05

String.Format Trap - Incorrect Handling of Input

Developers sometimes fall into this trap:
string input = "First Last";
string fmt = "Your {0} is: " + input;
string out = String.Format(fmt, "name");
There's nothing wrong with this code, right?

WRONG.

What happens if input looks like this?
string input = "First Last {1}";
Well, String.Format will look for another parameter... BANG!
An exception is thrown.

The correct way to use input parameters for String.Format (and all printf-like functions, for that mater) is as follows:
string input = "First Last";
string fmt = "Your {0} is: {1}";
string out = String.Format(fmt, "name", input);
Put the input as a parameter to the format and at least this type of attack can be avoided!