asp.netcreatechildcontrols

what will happen if we don't call base.createchildcontrols()


I just would like to know what will happen if we don't put base.createchildcontrols() in the code. Will composite control be created without calling base.createchildcontrols()?

 [ToolboxData("<{0}:Login runat=server></{0}:Login>")]
public class Login : CompositeControl
{
 private TextBox txtUsername = new TextBox();
private TextBox txtPassword = new TextBox();
private Button btnLogin = new Button();

protected override void CreateChildControls()
{
txtUsername.ID = "txtUsername";
txtPassword.ID = "txtPassword";
txtPassword.TextMode = TextBoxMode.Password;
btnLogin.ID = "btnLogin";
btnLogin.Text = "Login";

Controls.Add(txtUsername);
Controls.Add(txtPassword);
Controls.Add(btnLogin);

base.CreateChildControls();
 }
  }

Solution

  • The short answer is... Nothing! You don't need to call the base implementation (although you can always try removing it to see what happens ;-)

    Using ILSpy, we can see that CompositeControl inherits from WebControl which inherits from Control.

    CreateChildControl() is defined on Control as:

    protected internal virtual void CreateChildControls()
    {
    }
    

    i.e. It is only there to be overriden.

    Compare this with some other controls that inherit from Control, like BaseDataList and you can see that that method has a lot of functionality for checking and rendering the output.

    This makes sense. Reading the MSDN documentation, here, we can see that it is for you to implement the rendering of any child controls. Only if the class you are inhereting from requires this method to be called, then you'll have to call it.