Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to mark overridden method as final

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?

like image 926
dbkk Avatar asked Apr 28 '09 12:04

dbkk


People also ask

Can an overridden method be final?

No, the Methods that are declared as final cannot be Overridden or hidden.

What happens when final method is overridden?

A method declared with the final keyword, then it is known as the final method. The final method can't be overridden. A final method declared in the Parent class cannot be overridden by a child class. If we try to override the final method, the compiler will throw an exception at compile time.

Can we override already overridden method?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.


2 Answers

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 } 
like image 160
Lucero Avatar answered Sep 20 '22 13:09

Lucero


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 } 
like image 37
Ryan Emerle Avatar answered Sep 20 '22 13:09

Ryan Emerle