March 22nd, 2006

ASP.Net – Easy String Formatting

With classic ASP, string formatting and concatenation can be more than a pain. Line after line of 'strSQL = strSQL & "more text"' can be painful and very problematic. With ASP.Net and C# however, I've recently discovered the beauty of string.Format(), and just how easy it is to build strings with it.

With old-school ASP, you may have some code like this:


strSQL = "SELECT FROM articles WHERE topic = '" & strTopic & "'"

if strAuthor <> "" then
     strSQL = strSQL & " AND author = '" & strAuthor & "'"
end if

OK, that's easy enough. But when you're querying or inserting with many parameters/values, things can get messy. So with C#, you can do the same with slightly neater code:


string strSQL = "SELECT FROM articles WHERE topic = '" + strTopic + "'";

if (strAuthor != "")
     strSQL += " AND author = '" + strAuthor + "'";

BUT, with string.Format() you can create very efficient easy code:


string condAuthor = (strAuthor != "" ? "" : " AND author = '" + strAuthor + "'");
string strSQL = string.Format("SELECT FROM articles WHERE topic = '{0}'{1}", strTopic, condAuthor);

Using string formatting, you can place as many {#} arguments in the text as you want, and specify them afterwards. C# automatically insterts them into the text. Very clean.

Share

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word