Why use TagBuilder instead of StringBuilder?

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?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)