Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you call base.Method() in overridden method, and how to mark this when you write code in team? [closed]

Tags:

When using some framework/api, sometimes it's pretty unclear if you must call base.Method if you override it, for example you can be pretty sure that you should call base.Maethod() when you are overriding event invocater, to propagate the event, in other situations it can be not so clear especially when there is no source code available, and no comments.

I wounder how other programmers decide should they call base method or not in this situation, and if you are about to write some framework how to inform other programmers that you expect base method to be called or not in virtual members.

like image 866
Alex Burtsev Avatar asked Jan 18 '11 07:01

Alex Burtsev


People also ask

How do we identify if a method is an overridden method?

getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.

Which keyword do you use to declare a method or property that can be overridden by a derived class?

The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.

Which of the following keywords allows a derived class to access a base class method even when the base class has overridden the derived class method?

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.


2 Answers

Nowadays I don't think that consumers of a class that override a method should ever need to call base.Method(). The code should be written in such way that it cannot be broken.

public class MyBase {     private void FooInternal()     {         DoRequiredStuff();         Foo();     }     public virtual void Foo() {} } 
like image 112
Alex Burtsev Avatar answered Sep 20 '22 05:09

Alex Burtsev


If you are requiring that consumers of your class MUST implement functionality of a particular method, that method should be marked abstract.

If consumers of your class should optionally provide functionality of a particular method, that method should be virtual.

There is really no way to require that a consumer of a class call a base.Method() on a virtual method. It really depends on context. If the base.Method() does some work that you'd otherwise have to do, it'd behoove you to call base.Method() if that would save you some development time/it makes sense in that context.

like image 23
Mike Corcoran Avatar answered Sep 21 '22 05:09

Mike Corcoran