When you override a method, you shouldn’t change the behaviour of the method, you just specialise it. Therefore you have to call base.MyVirtualMethod() in the overridden method and add the specialisation code.
But I’m always wondering when I have to call the base.MyVirtualMethod(). Or from another point of view, how do I write my virtual method? Should I expect the user will call it as the first or the last thing the overridden method does?
public class Parent
{
public virtual void MyMethod(){ /* Some code*/ }
}
public class Child : Parent
{
public override void MyMethod()
{
/* Does my code goes here? */
base.MyMethod();
/* Or does my code goes here? */
}
}
That is not always true – there are cases when you don’t want to do in the derived class what the superclass is doing so you don’t want to call
base.If you want to extent the base behavior you place your code before or after
basecall, depending on the actual problem. There is no rule ‘always call base before your code’.