views:

642

answers:

4

I understand overriding a method/function redefines its implementation in the derived class from its implementation in the base class.

Now what confuses me, is if I override a class in ASP.NET such as CreateChildControls() (I picked it randomly for no particular reason), VS2008 auto generates:

protected override void CreateChildControls()
{
   base.CreateChildControls();
}

Good enough, the default implementation just calls the base class' CreateChildControls().

So if I want to run some code, since I do not know how base.CreateChildControls(), should I do this:

protected override void CreateChildControls()
{
   /*My Code Here*/                    
   base.CreateChildControls();
}

or, ignore what base.CreateChildControls() altogether and just do

protected override void CreateChildControls()
{
   /*My Code Here*/                    
}
+7  A: 

That's up to you. Generally, you want to call the base class method because it might do a lot of stuff you're not privy to (especially in a class you don't control .. get it? Control.) But, if you are very confident you don't need (or want) the base class "stuff" to happen, you can remove the call.

JP Alioto
It's really surprising to me that you would be allowed to override a base class you are not privy to.
Matt
I have to have that freedom. Just because I am your child, does not mean I want to do everything like you do. Sometimes, I need to go out in the world and do things my own way. You would be an overprotective parent if you forced me to have your implementation. :)
JP Alioto
+2  A: 

It's simply a question of whether you want to entirely replace the behavior or add behavior.

For something like CreateChildControls, you will probably retain the call to the base class.

Larsenal
+1  A: 

it depends on what you want to do. If you want the base.CreateChildControls() method to be called and then you want to perform some custom action before or after the method is called, then you can do so.

If you want to have complete control of what is happening when CreateChildControls is called, then you can simply ignore calling it altogether.

The fact that it's in there by default is just a bit of guidance for you.

lomaxx
A: 

It depends if you want to replace or complete the base implementation... in most cases you should call the base implementation (and you definitely should do it in the case of the CreateChildItems method...)

Thomas Levesque