There is no great reason. I would say speed, because TagBuilder is essentially a specialized StringBuilder , which is known to be faster than string.Format , but I will need to see some benchmarks, since it seems that the whole structure of the HTML object can slow down.
One example of why you can use it is that it simplifies conditional logic. I think, for example, something like
var theClass = item.Title.Length > 5 ? " class=\"Long\"" : ""; var str = string.Format(@"<li><a href=""{0}""{1}>{2}</a></li>", item.Uri, theClass, item.Title);
not very clear or clean, whereas
if (item.Title.Length > 5) { a.AddCssClass("Long"); } // And then all that other stuff.
- a pretty nice solution.
source share