Understanding the 'sealed' Keyword in C#

C# sealed Keyword

The sealed keyword is used to restrict inheritance and prevent a class from being used as a base class for further derivation. When you mark a class as sealed, it becomes a "terminal" class, and other classes cannot inherit from it. This is often done to prevent unintended modifications or extensions of critical classes in the inheritance hierarchy.

Usage of the sealed keyword:

public sealed class SealedClass
{
    // Class members and methods go here.
}

In this example, SealedClass is marked as sealed, indicating that it cannot be inherited by other classes. Any attempt to derive a class from SealedClass will result in a compilation error.

Key points to note about sealed:

  1. The sealed keyword can only be applied to classes and methods. It cannot be used with fields or properties.

  2. A sealed class can still inherit from other classes. However, since it is sealed itself, it prevents any further derivation from it.

  3. It is possible to use the sealed keyword with methods in a derived class. This indicates that the method cannot be further overridden in any class that derives from the current class.

Here's an example of using the sealed keyword with a method:

public class BaseClass
{
    public virtual void MethodToOverride()
    {
        // Method implementation in the base class.
    }
}

public class DerivedClass : BaseClass
{
    public sealed override void MethodToOverride()
    {
        // Method implementation in the derived class.
        // This method cannot be overridden further in any derived classes.
    }
}

In this example, the DerivedClass overrides the MethodToOverride method from the BaseClass and marks it as sealed. As a result, any class that derives from DerivedClass cannot further override the MethodToOverride.

Using the sealed keyword provides a way to control the inheritance hierarchy and ensure that certain classes or methods cannot be extended or modified in unintended ways. It promotes code stability and helps in maintaining well-defined class hierarchies in large projects.