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.
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.
Yes, just leave the class public and make the method sealed.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With