Search code examples
c#polymorphismvirtual

Call a virtual method from its overridden


In order to call the base virtual method from its overridden one, how should I define the instance?

Assume I have class Derived which extends Base class. I have a virtual method in Base which is overrided in class Derived.

Like this : Base instance = new Derived();

or like this: Derived instance = new Derived();

For sure I shall not use Base instance = new Based(); for it call the virtual methos and not its override.


Solution

  • Whether a method override calls the implementation of the base class does not depend on the type of variable you use. So, as soon as you add base.MethodName() to the implementation of the override, the first two ways you describe will be ok.

    As you also mention, the third approach will not work as it does not call the overridden version of the method.