Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

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!

Posted: Sep 29 2004, 06:43 PM by Manoj G | with 9 comment(s)
Filed under:

Comments

Manoj G said:

Thanks for the tip.
# November 29, 2004 11:57 AM

Manoj G said:

Good One ! Thanks!
# January 4, 2005 4:23 PM

Manoj G said:

I do not think its less error prone, in fact I'd suggest for basic cases like this it is more error prone. However I do agree that it is a better method, especially when it comes to updating code or making certain string formats configurable from outside the method that it will be called in.
# January 13, 2005 8:12 AM

Manoj G said:

Just came across this post while looking for the "{{" escape format... Thanks! But I couldn't help but see you were using string.Format to construct a SQL statement. :O I have just given a talk with the ASP.NET team about SQL Injection attacks (http://www.styledesign.biz/weblogs/macinnesm/archive/2005/03/07/312.aspx) and while I appreciate this is just an example, developers might come across this usage and think its ok. NEVER use string.Format to construct SQL statement as this leads to a major security vulnerability in which users may take complete control of the database.
# March 15, 2005 3:39 PM

Manoj G said:

Just wondering how could that make difference to building sql statements using string.format v/s. a simple method of constructing string using sinlge quote and double quotes.

:)
# May 15, 2005 3:15 AM

Manoj G said:

Simple and Easy to understand
# June 16, 2005 4:56 PM

Manoj G said:

Don't use String.Format --OR-- string concatenation. To protect from SQL Injection as mentioned above, always use Parameters. You can even use Parameters in text commands, they don't have to be stored procedures. Parameters also have a convention as easy to use as the {n} format used in String.Format. With SQL Server, use regular SQL variable like @EmployeeID and with others use the ODBC ? as a placeholder.
# June 19, 2005 8:54 AM

Laoujin said:

You could just use string concatenation you just have to be careful to escape any possible attacks.

string.Format("SELECT * FROM table WHERE field='{0}'", userInput.Replace("'", "''"))

I'm sure there are better methods then the Replace in .NET but that would be perfectly save.

# December 19, 2007 5:05 AM

visitor said:

2 points.

1. watch out for {0) which looks a lot like {0} which if you're typing fast can happen quite frequently...will result in a very strange message you could end up surfing around for hours trying to find what's wrong...not that that's happened to me or anything.

2. as far as sql injection we do something like this:

String.Format("sql goes here where id = {0}", SqlTool.StringToSQL(m_String));

and have a separate class that handles the '' stuff... this allows you to escape things neatly behind the scenes, still use string.format, and keep code consistent, and still use intellisense to make things speedy...

# April 23, 2008 9:50 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)