views:

706

answers:

4

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?

+25  A: 

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
}
Lucero
Great, I didn't know of that language feature :)
dbkk
+4  A: 

You need "sealed".

RichieHindle
+2  A: 

You can mark the method as sealed.

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

Ryan Emerle
you can make individual methods sealed in fact
annakata
why would you mark the class as sealed ? You can specify this modifier at the method level as well ...
Frederik Gheysels
Interesting I've never known you could seal methods however I've never had a reason to.
Chris Marisic
+2  A: 

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
  }
}
serg10