Tim
Tim

Reputation: 99408

Does a method declared as `override` remain `virtual`?

is a method declared with override still virtual?

For example

class C1 {

public virtual void MyMethod()
{
}

}

class C2: C1 {

public override void MyMethod()
{
}

}

Does MyMethod defined in C2 remain virtual as the method defined in C1 which it overrides? i.e. Can it be overridden by a method in a class derived from C2?

If not, how can I make it virtual?

Upvotes: 1

Views: 82

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 27009

Yes you can override it but once you seal it, then you can no longer override it if you derive from the sealed version:

public class C1 {

  public virtual void MyMethod() {
  }

}
public class C2 : C1 {
  public sealed override void MyMethod() {
     base.MyMethod();
  }
}

Below will not work:

public class C3 : C2 {
  // here you will no longer be able to override it
}

But if other classes derive C1, that will still work.

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190925

Yes. You can continue to override it as many times as you need to in subsequent subclasses.

From the C# 5.0 spec (my emphasis):

A virtual method can be overridden in a derived class. When an instance method declaration includes an override modifier, the method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of that method.

Section 10.6.5 talks about what CodingYoshi is referring to, but it shows an example that it can be done.

Upvotes: 1

Related Questions