Preventing a method from being overridden in C#

nighthawk457 picture nighthawk457 · Mar 28, 2012 · Viewed 33.5k times · Source

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.

Answer

Kendall Frey picture Kendall Frey · Mar 28, 2012

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.