Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Methods in Multi-level Inheritence

Tags:

c#

Given three parent/child classes, like this:

class A {
    public virtual void doSomething() {
        //do things
    }
}

class B : A {
    public override /*virtual?*/ void doSomething() {
        //do things
        base.doSomething();
    }
}

class C : B {
    public override void doSomething() {
        //do things
        base.doSomething();
    }
}

Should class B's doSomething() method have both override and virtual in its signature, since it also is overridden by the C class, or should only class A have virtual in its doSomething() method signature?

like image 421
Ian Baer Avatar asked Dec 11 '13 23:12

Ian Baer


2 Answers

You don't need to (read: you can't) mark a method as virtual, if it has already been marked as virtual in one of the super classes.

The method will remain virtual throughout the inheritance tree until a subclass marks it as sealed. A sealed method cannot then be overridden by any of the subclasses.

like image 123
dcastro Avatar answered Sep 18 '22 17:09

dcastro


From MSDN:

You cannot use the new, static, or virtual modifiers to modify an override method.

Also,

The overridden base method must be virtual, abstract, or override.

Meaning that you can override a method that is already marked as override.

like image 45
Will Faithfull Avatar answered Sep 17 '22 17:09

Will Faithfull