ASP.NET Rendered Controls vs. Composite Controls – I prefer to avoid rendered controls – level 200

Here, I’ll present a simple example of the same control using the rendered method and the composite method.  For those new to custom web controls, a rendered control is a class inherited from “Control” or “WebControl” that overrides the “Render” method in order to sned custom markup to the browser.  A composite control uses other controls in a hierarchy and leaves the rendering to each control. 

Here is a simple rendered control:

    6     public class RenderedControl : Control

    7     {

    8         protected override void Render(HtmlTextWriter writer)

    9         {

   10             writer.AddAttribute(HtmlTextWriterAttribute.Id, “myID”);

   11             writer.RenderBeginTag(HtmlTextWriterTag.Div);

   12             writer.AddAttribute(HtmlTextWriterAttribute.Id, “innerID”);

   13             writer.RenderBeginTag(HtmlTextWriterTag.Span);

   14             writer.Write(“This text is the meat of this control.”);

   15             writer.RenderEndTag();

   16             writer.RenderEndTag();

   17         }

   18     }

It’s pretty straight-forward, and the output will always be this: 

   18 <div id=”myID”>

   19     <span id=”innerID”>This text is the meat of this control.</span>

   20 </div>

Here is the same thing using the composite method:

    6     public class CompositeControl : Panel

    7     {

    8         protected override void CreateChildControls()

    9         {

   10             base.CreateChildControls ();


   12             this.ID = “myID”;


   13             Label lbl = new Label();

   14             lbl.ID = “innerID”;

   15             lbl.Text = “This text is the meat of this control.”;


   16             this.Controls.Add(lbl);

   17         }

   18     }

With the composite method, the developer doesn’t have to worry about the low level markup being rendered, and he can depend on the richer object-oriented contract of each child control.  With this method, the developer overrides the CreateChildControls() method and adds child controls.  All these child controls will render themselves.  The exact same markup renders.

In my opinion, using the composite control method optimizes development time, and that is the most expensive more often than not.  I don’t give weight to the performance argument because the difference in performance is on the millisecond scale.  The moment you call out-of-process to a database or the file system, you accept a performance hit of much more magnitude; therefore, the performance difference of these two methods is negligible.  The composite control method is more maintainable, and maintenance of an application always costs more.