What Is Sealed Class In C#?

Sealed classes

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.

Advantages of using sealed classes in C#

Type safety

By sealing a class, you can ensure that the class cannot be used as a base class for any other class, providing a stronger level of type safety.

Performance optimization

The C# compiler can make certain optimizations when it knows that a class is sealed, leading to improved performance in some cases.

Protection of class implementation

Sealing a class provides protection for its implementation and behavior, ensuring that it cannot be modified or overridden in any way by derived classes.

Limitations of Using Sealed classes 

Limited Inheritance

Sealed classes cannot be inherited by other classes, thus limiting the scope for reuse and modularity.

Decreased Flexibility

Since sealed classes cannot be inherited, it can lead to decreased flexibility in certain scenarios where inheritance is required.

Not Available in All Languages

Sealed classes are a feature of some programming languages like C# and are not available in other programming languages like Java, which makes them less portable.

Debugging Issues

Debugging can be more challenging in sealed classes as the code is not as easily inspectable as in other open classes.

sealed class SealedClassName
{
    // class members
}
sealed class Circle {
    public double Radius {
        get;
        set;
    }
    public double CalculateArea() {
        return Math.PI * Radius * Radius;
    }
}

Summary

A sealed class is a class that is restricted from being inherited by other classes. The "sealed" keyword is used to declare a class as sealed. 

The purpose of sealed classes is to prevent inheritance, which can be useful in certain situations where you want to ensure that a class cannot be extended or modified in unexpected ways. For example, if you have a class that implements a critical algorithm and you want to ensure that its behavior remains consistent, you can declare the class as sealed.


Similar Articles