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 understan
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
}
You need "sealed".
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
}
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
}
}