Tuesday, November 23, 2004

String.Format : Useful Tips

It is very tedious job, reading the code which have more string concatenation (if single and doubl;e quotes are also there..it will be more congested).
A simple case is shown below:

string strSQL = "Insert into Table1 Values ('" + strVal1 + "', '" + strVal2 + "')";

A much better approach would be to use the string.Format method which makes concatenations much more readable and will reduce the possibility of error.

The same example can be replaced with:

string INSERT_FORMAT = "Insert into Table1 Values ('{0}', '{1}')";
string strSQL = string.Format(INSERT_FORMAT,strVal1,strVal2);

Create placeholders by inserting {n} into the string, where n describes the position of the replacement parameter.The StringBuilder too comes with the AppendFormat which serves the same purpose.

Now, here is a small catch. What happens if the format string itself has "{" or "}".


string strProblemFormat = "{Now, this is a problem}, {0}";

In this case, you would end up getting a FormatException.


Solution is simple. Escape "{" with "{{" and "}" with "}}" in your format string.

string strProblemFormat = "{{Now, this is a problem}}, {0}";
string strDisplay = string.Format(strProblemFormat,"Not anymore!");