3
class X {
    sealed protected virtual void F() {
        Console.WriteLine("X.F");
    }
    sealed void F1();
    protected virtual void F2() {
        Console.WriteLine("X.F2");
    }
}

In the above code there is compile time error :

X.F()' cannot be sealed because it is not an override

X.F1()' cannot be sealed because it is not an override

Does it mean we can only apply the sealed keyword whey we have to override some methods?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Bh00shan
  • 488
  • 6
  • 20
  • 2
    The MSDN entry for [sealed](https://msdn.microsoft.com/library/88c54tsw.aspx) seems pretty clear. Sealing a virtual method does not make sense (why make it virtual and then prevent overriding?). And sealing a "normal" method also does not make sense, since by default you can't override it anyway. That leaves the scenario that you want (and do) override a method but say "anything inheriting from me must not override this method any further". That's what `sealed override` is for. – Corak Feb 18 '16 at 07:48
  • What is it that you want to do with this code? Maybe there's a different way to accomplish your goal. – yesman Feb 18 '16 at 07:58

1 Answers1

5

Well, sealed keyword prevents method from being overriden, and that's why it doesn't make sence

  1. with virtual declaration - just remove virtual instead of declaring virtual sealed.
  2. on abstract methods, since abstract methods must be overriden
  3. on non-virtual methods, since these methods just can't be overriden

So the only option is override sealed which means override, but the last time:

public class A {
  public virtual void SomeMethod() {;}

  public virtual void SomeOtherMethod() {;}
}

public class B: A {
  // Do not override this method any more
  public override sealed void SomeMethod() {;}

  public override void SomeOtherMethod() {;}
}

public class C: B {
  // You can't override SomeMethod, since it declared as "sealed" in the base class
  // public override void SomeMethod() {;}

  // But you can override SomeOtherMethod() if you want
  public override void SomeOtherMethod() {;}
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215