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.
You don’t need to do anything. The
virtualmodifier specifies that a method can be overridden. Omitting it means that the method is ‘final’.Specifically, a method must be
virtual,abstract, oroverridefor it to be overridden.Using the
newkeyword will allow the base class method to be hidden, but it will still not override it i.e. when you callA.methodB()you will get the base class version, but if you callB.methodB()you will get the new version.