C# Sealed Class & Method

In C#, a sealed class is a class that cannot be inherited. Once a class is marked as sealed, it cannot be used as a base class for any other class. To define a sealed class, you use the sealed keyword in front of the class definition.

Here's an example:

sealed class MySealedClass
{
    // class implementation
}
Source:‮‬www.theitroad.com

In this example, the MySealedClass is defined as a sealed class. No other class can inherit from this class.

A sealed method is a method that cannot be overridden in a derived class. When a method is sealed, it means that the implementation of the method in the base class cannot be changed or extended by the derived class. To define a sealed method, you use the sealed keyword in front of the method definition.

Here's an example:

class MyBaseClass
{
    public virtual void MyMethod()
    {
        // implementation of MyMethod
    }
}

class MyDerivedClass : MyBaseClass
{
    public sealed override void MyMethod()
    {
        // implementation of MyMethod in the derived class
    }
}

In this example, the MyDerivedClass class inherits from the MyBaseClass class and overrides the MyMethod method. The MyMethod method in the MyDerivedClass class is sealed, which means that it cannot be overridden by any further derived classes.

Sealed classes and methods are useful when you want to prevent further inheritance or overriding of a class or method. This can help to ensure that the implementation of a class or method remains consistent and cannot be changed by other developers.