Friday, April 24, 2009

Short Rant on StringBuilder and String

I’ve been running into lots of code which seems to be using Strings to build up HTML or Error Messages.  Unfortunately there is lots of inconsistency in the way it’s been done, but for anyone interested here is my take on it.  First off let me say any hard coding HTML into a code behind is generally a bad idea (don’t get me wrong I’ve done it myself lots of time) so try to avoid it at much as possible.  If however you are unable to avoid it, please review the examples below and try to keep to using the “Good” technique.

The Good

Here is a reasonably good example of code for building HTML in a code behind if you can’t avoid it.  Using StringBuilder is faster and better suited for concatenation than the primitive String type.  Also using the AppendFormat function allows you to use the {#} place mark which ensures your value goes into the correct location, making the string far more readable and maintainable.

StringBuilder sbTemp = new StringBuilder();
sbTemp.AppendFormat("<a href=\”mailto:{0}\”>{1}</a>",
                                                          ConfigurationManager.AppSettings["IT_EMAIL"],
                                                          ConfigurationManager.AppSettings["IT_EMAIL"]);
litITEmail.Text = sbTemp.ToString();

 

The Bad

Here is a bad example of the same code using String Builder.  although it will accomplish the same goal as above it requires more code and is much more difficult to read or maintain.
sbTemp.Append("<a href=\"mailto:");
sbTemp.Append(ConfigurationManager.AppSettings["IT_EMAIL"]);
sbTemp.Append("\">");
sbTemp.Append(ConfigurationManager.AppSettings["IT_EMAIL"]);
sbTemp.Append("</a>");
litITEmail.Text = sbTemp.ToString();

 

The Down Right Ugly (and wrong on so many levels)

Here is the wrong way to do it and anyone doing this should be taken out and shot.
string s = "<a href=\"mailto:";
s += ConfigurationManager.AppSettings["IT_EMAIL"];
s += "\">";
s += ConfigurationManager.AppSettings["IT_EMAIL"];
s += "</a>";
litITEmail.Text = s;