C# sealed class and methods

In C# we can make the class and methods sealed. When a C# class becomes sealed it can't be inherited by any child class. In the same way, if a method is declared as a sealed method then it can' t be overridden.

Sealed Class

By using the sealed keyword a class can be declared as sealed.

Following is an example of sealed class.

sealed class Gravity
{
    //Gravity state and behavior
}
 
class newGravity : Gravity //Inheritance is not possible
{
        
}

The common reason behind creating a sealed class is to restrict the user to modify the state or behavior of a class. Either by inheriting or overriding the functionality.

Sealed Method

Like we declare the classes sealed, by using the sealed keyword method can also be marked as a sealed method. If a method is marked as a sealed method then can't be overridden.

Following is an example of a sealed method.

class MyCustomerClass : MyClassBase
{
    public sealed override void FinalMethod()
    {
        // body.
    }
}
class DerivedCustomerClass : MyCustomerClass
{
    public override void FinalMethod() // wrong. Will throw a compilation error
    {
    }
}

Let's learn about the virtual methods in the next section.