Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call base method at beginning or end of method?

The only similar question to this I found was this and the answer suggested having to use Reflector to find out.

What about in just the majority of the cases? Generally, is the base method called first or last in a method?

I noticed in some libraries it is called at the beginning at the method and in the XNA Framework they're called at the end of methods (base.Update, base.Draw, et cetera).

like image 523
Ryan Peschel Avatar asked Oct 17 '11 19:10

Ryan Peschel


People also ask

How do you call a base method in C#?

base (C# Reference)The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.

How can we call the base method without creating an instance?

Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.


2 Answers

It depends on whether you want you derived behaviour to happen before or after the base behaviour.

And don't forget you can call the base method in the middle or not at all.

Having said that, in general it will be called as the first thing. Because then your overriding method has the option to 'overwrite' settings done by the base-class.

But in methods like Close or Dispose it is more customary (sometimes mandatory) to call it in the end.

like image 77
Henk Holterman Avatar answered Sep 19 '22 23:09

Henk Holterman


It entirely depends on what you want to do. There's not really a "general" rule about what should happen. For example, you might want to do some extra validation, then call the base method, then do something else. Or maybe you just want to time how long the base method takes to call.

Treat each case as an individual situation.

like image 34
Jon Skeet Avatar answered Sep 19 '22 23:09

Jon Skeet