String.Format: A Simple Tip
More often than not, we end up concatenating strings in our application code, and a bit aggressively. Sometimes, these concatenations can get a ugly, resulting into a mire of single quotes, double quotes and escape sequences. A simple case of not-so lucid concatenation is shown below:
string consoleMessage = "Time taken by operation: " + operation + " under category: " + category + " :" + time.ToString() + " ms";
A much better approach would be to use the string.Format method which makes concatenations much more readable and less error prone. The same example can be replaced with:
string consoleMessage = string.Format("Time taken by operation: {0} under category {1}: {2} ms", operation, category, time);
Simple. Create placeholders by inserting {n} into the string, where n describes the position of the replacement parameter.The StringBuilder too comes with the AppendFormat method which serves the same purpose. Now, here is a small catch. What happens if the format string itself has "{" or "}"?
strProblemFormat = "{Now, this is a problem}, {0}";
In this case, you would end up getting a FormatException. The solution however, 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!");
[Updated] I got a lot of flak for chosing a SQL example for string concatenation! As many of the comments rightly indicate, concatenations on SQL statements could potentially invite SQL injection attacks. Parameterized SQL in such cases is a better choice. Thanks for the feedback!