title: Using HtmlTextWriter to Render Server Controls?
body: <p>I'm writing the <code>RenderContents()</code> method of my ASP.NET server control. The method uses an <code>HtmlTextWriter</code> object to render the output content. For the control I'm writing, using the <code>HtmlTextWriter</code>'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.</p>
  
  <p>I was thinking that if I used a chainable class such as <code>StringBuilder</code>, my code would be a lot cleaner to read and easier to write.</p>
  
  <p>What I was wondering was, is there any reason to use the <code>HtmlTextWriter</code> 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.</p>
  
  <p>It seems like it would be easier to just do something like this:</p>
  
  <pre><code>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();
  }
  </code></pre>
  
  <p>Is there any reason why this would be a bad idea?</p>
  
  <p><strong>Update</strong><br>
  In response to <a href="https://stackoverflow.com/questions/489691#489711">Mehrdad Afshari</a>'s answer:<br>
   I didn't think much about the memory requirements of having a separate <code>StringBuilder</code> object instantiated. What about making a wrapper for HtmlTextWriter so that it can be chained so that an extra string isn't made.</p>
  
  <pre><code>public class ChainedHtmlTextWriter
  {
      private HtmlTextWriter _W;
      public ChainedHtmlTextWriter(HtmlTextWriter writer)
      {
          _W = writer;
      }
  
      public ChainedHtmlTextWriter Write&lt;T&gt;(T value) 
      { 
          _W.Write(value); 
          return this; 
      }
  
      public ChainedHtmlTextWriter WriteLine&lt;T&gt;(T value)
      {
          _W.WriteLine(value);
          return this;
      }
  }
  </code></pre>