Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call the base class implementation when overriding a method in C# for ASP.NET?

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*/                    
}
like image 747
Matt Avatar asked Jul 09 '09 23:07

Matt


People also ask

How do you call base class method overriding?

Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.

Would you override a method of a base class?

Method overriding limitations Both the parent class and the child class must have the same method name, the same return type and the same parameter list. Methods declared final and static cannot be overridden. A method cannot be overridden if it cannot be inherited. That is, it must be an IS-A relationship.

Why would override a method of a base class?

Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.

How can we call base class method after overriding in C#?

class A { virtual void X() { Console. WriteLine("x"); } } class B : A { override void X() { Console. WriteLine("y"); } } class Program { static void Main() { A b = new B(); // Call A.X somehow, not B.X... }


2 Answers

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.

like image 188
JP Alioto Avatar answered Sep 18 '22 10:09

JP Alioto


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.

like image 22
Larsenal Avatar answered Sep 20 '22 10:09

Larsenal