is it possible to mark overridden method as final
Asked Answered
G

4

48

In C#, is it possible to mark an overridden virtual method as final so implementers cannot override it? How would I do it?

An example may make it easier to understand:

class A
{
   abstract void DoAction();
}
class B : A
{
   override void DoAction()
   {
       // Implements action in a way that it doesn't make
       // sense for children to override, e.g. by setting private state
       // later operations depend on  
   }
}
class C: B
{
   // This would be a bug
   override void DoAction() { }
}

Is there a way to modify B in order to prevent other children C from overriding DoAction, either at compile-time or runtime?

Gupta answered 28/4, 2009 at 12:2 Comment(0)
A
79

Yes, with "sealed":

class A
{
   abstract void DoAction();
}
class B : A
{
   sealed override void DoAction()
   {
       // Implements action in a way that it doesn't make
       // sense for children to override, e.g. by setting private state
       // later operations depend on  
   }
}
class C: B
{
   override void DoAction() { } // will not compile
}
Anthony answered 28/4, 2009 at 12:7 Comment(0)
O
11

You can mark the method as sealed.

http://msdn.microsoft.com/en-us/library/aa645769(VS.71).aspx

class A
{
   public virtual void F() { }
}
class B : A
{
   public sealed override void F() { }
}
class C : B
{
   public override void F() { } // Compilation error - 'C.F()': cannot override 
                                // inherited member 'B.F()' because it is sealed
}
Oosphere answered 28/4, 2009 at 12:7 Comment(3)
you can make individual methods sealed in factBriseno
why would you mark the class as sealed ? You can specify this modifier at the method level as well ...Eleonoraeleonore
Interesting I've never known you could seal methods however I've never had a reason to.Dock
B
8

You need "sealed".

Bahaism answered 28/4, 2009 at 12:7 Comment(0)
L
6

Individual methods can be marked as sealed, which is broadly equivalent to marking a method as final in java. So in your example you would have:

class B : A
{
  override sealed void DoAction()
  {
    // implementation
  }
}
Lombard answered 28/4, 2009 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.