Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing a method from being overridden in C#

Tags:

How do I prevent a method from being overridden in a derived class?

In Java I could do this by using the final modifier on the method I wish to prevent from being overridden.

How do I achieve the same in C#?
I am aware of using sealed but apparently I can use it only with the override keyword?

class A {     public void methodA()     {         // Code.     }      public virtual void methodB()     {         // Code.     } }  class B : A {     sealed override public void methodB()     {         // Code.     }  } 

So in the above example I can prevent the methodB() from being overridden by any classes deriving from class B, but how do I prevent class B from overriding the methodB() in the first place?

Update: I missed the virtual keyword in the methodB() declaration on class A when i posted this question. Corrected it.

like image 371
nighthawk457 Avatar asked Mar 28 '12 20:03

nighthawk457


People also ask

How do you prevent a method from being overridden?

Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated. An abstract class can contain abstract methods—methods that are declared but not implemented.

Can you allow a class to be inherited but prevent a method from being overridden in C#?

Yes, just leave the class public and make the method sealed.


2 Answers

You don't need to do anything. The virtual modifier specifies that a method can be overridden. Omitting it means that the method is 'final'.

Specifically, a method must be virtual, abstract, or override for it to be overridden.

Using the new keyword will allow the base class method to be hidden, but it will still not override it i.e. when you call A.methodB() you will get the base class version, but if you call B.methodB() you will get the new version.

like image 188
Kendall Frey Avatar answered Sep 17 '22 06:09

Kendall Frey


As you mentioned, you can prevent further overriding of MethodB in class B by using sealed with override

class B : A {     public sealed override void methodB()     {         Console.WriteLine("Class C cannot override this method now");     } } 

Use of the sealed modifier along with override prevents a derived class from further overriding the method.

If you do not want methodB in class A to be overridden by any child classes, do not mark that method virtual. Simply remove it. virtual keyword enable the method to be overridden in child classes

public void methodA() {        } 

Use sealed keyword on your classes to prevent further overriding of the class

like image 40
Shyju Avatar answered Sep 19 '22 06:09

Shyju