12 Feb 2024




Beginner

In C#, the sealed keyword is used to restrict inheritance. When you mark a class with the sealed keyword, it means that the class cannot be inherited by other classes. Similarly, when you mark a method with the sealed keyword, it means that the method cannot be overridden in derived classes.

Here's how you use the sealed keyword:

To seal a class:

sealed class MyClass
{
    // class members
}

In the above example, MyClass cannot be used as a base class for any other class.

To seal a method:

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

class MyDerivedClass : MyBaseClass
{
    public sealed override void MyMethod()
    {
        // Some implementation specific to MyDerivedClass
    }
}

class MyFurtherDerivedClass : MyDerivedClass
{
    // This class cannot override MyMethod
}

In the above example, MyDerivedClass can override MyMethod, but MyFurtherDerivedClass cannot further override MyMethod since it's sealed in MyDerivedClass.

The sealed keyword provides a way to prevent further inheritance or overriding in a class hierarchy. It's particularly useful when you want to enforce certain design decisions or ensure that a class or method behaves in a specific way without allowing further modifications through inheritance.

c-sharp
sealed