Preventing override of individual methods in C#

Only virtual methods can be overridden.
Just leave out virtual, and your method will not be overridable.


you can also use sealed modifier to prevent a derived class from further overriding the method.

check this out: Sealed methods


Yes. The sealed keyword can also be used on methods, to indicate that a method which is virtual or abstract at higher inheritance levels cannot be further inherited.

If the method was never virtual or abstract to begin with, no worries; it can't be overridden.

Note that sealed only affects method overriding; method hiding cannot be stopped in this way, so a child class can still declare a new method of the same name and signature as your sealed method.


You can get the sealed keyword to work on a method in the abstract class by making that abstract class itself derived from something:

abstract class DocumentTemplateBase
{
    public abstract void WriteTitle();
    public abstract void WriteSections();
}

abstract class DocumentTemplate : DocumentTemplateBase
{
    public override sealed void WriteTitle() 
    {
        Console.WriteLine("Project document"); 
    }

    public override sealed void WriteSections() 
    {
        Console.WriteLine("Sections");
    }

    abstract public void WriteContent();
}

Still deriving your concrete class from the original (and now derived) abstract class:

class Document1_FromTemplate : DocumentTemplate
{
    public override void WriteTitle() //error!
    {
        Console.WriteLine("Project1 document");
    }

"cannot override inherited member 'Dynamics.DocumentTemplate.WriteTitle()' because it is sealed"

There is nothing, however to prevent an implementer from newing it:

class Document1_FromTemplate : DocumentTemplate
{
    public new void WriteTitle() //sorry! can't stop it!
    {
        Console.WriteLine("Project1 document");
    }

You can use the sealed keyword in two ways:

  1. Before a class to avoid inheritance.
  2. Before a function to avoid overriding.

To allow inheritance don’t put the sealed keyword before the class and to avoid overriding put sealed before the function which you don’t want to be overridden.