Ian Baer
Ian Baer

Reputation: 117

Overriding Methods in Multi-level Inheritence

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?

Upvotes: 8

Views: 5416

Answers (2)

dcastro
dcastro

Reputation: 68660

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.

Upvotes: 10

Will Faithfull
Will Faithfull

Reputation: 1908

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.

Upvotes: 6

Related Questions