Why use TagBuilder instead of StringBuilder?

DaveDev picture DaveDev · Jun 15, 2010 · Viewed 22.2k times · Source

what's the difference in using tag builder and string builder to create a table in a htmlhelper class, or using the HtmlTable?

aren't they generating the same thing??

Answer

Bashir Magomedov picture Bashir Magomedov · Jun 15, 2010

TagBuilder is a class that specially designed for creating html tags and their content. You are right saying that result will be anyway a string and of course you still can use StringBuilder and the result will be the same, but you can do things easier with TagBuilder. Lets say you need to generate a tag:

<a href='http://www.stackoverflow.com' class='coolLink'/>

Using StringBuilder you need to write something like this:

var sb = new StringBuilder();
sb.Append("<a href='");
sb.Append(link);
sb.Append("' class = '");
sb.Append(ccsClass);
sb.Append("'/>");
sb.ToString();

It is not very cool, isn’t it? And compare how you can build it using TagBuilder;

var tb = new TagBuilder("a");
tb.MergeAttribute("href",link);
tb.AddCssClass(cssClass);
tb.ToString(TagRenderMode.SelfClosing);

Isn't that better?