I'm writing the RenderContents()
method of my ASP.NET server control. The method uses an HtmlTextWriter
object to render the output content. For the control I'm writing, using the HtmlTextWriter
's methods seems like it will require a lot of lines of code to open and close every tag and add every attribute to the stream. In the end I feel like I'm going to end up with code that is a lot longer than it needs to be.
I was thinking that if I used a chainable class such as StringBuilder
, my code would be a lot cleaner to read and easier to write.
What I was wondering was, is there any reason to use the HtmlTextWriter
object to render my entire control's contents? Other than the safety checks (I'm assuming) it includes to make sure you don't write tags in the wrong order or create invalid markup, I don't see a reason.
It seems like it would be easier to just do something like this:
protected override void RenderContents(HtmlTextWriter output)
{
StringBuilder s = new StringBuilder();
s.Append("lots")
.Append("of")
.Append("strings");
output.BeginRender();
output.Write(s.ToString());
output.EndRender();
}
Is there any reason why this would be a bad idea?
Update
In response to Mehrdad Afshari's answer:
I didn't think much about the memory requirements of having a separate StringBuilder
object instantiated. What about making a wrapper for HtmlTextWriter so that it can be chained so that an extra string isn't made.
public class ChainedHtmlTextWriter
{
private HtmlTextWriter _W;
public ChainedHtmlTextWriter(HtmlTextWriter writer)
{
_W = writer;
}
public ChainedHtmlTextWriter Write<T>(T value)
{
_W.Write(value);
return this;
}
public ChainedHtmlTextWriter WriteLine<T>(T value)
{
_W.WriteLine(value);
return this;
}
}