What is sealed Class in C#?

In C#, a sealed class is a class that cannot be inherited by other classes. When a class is marked as sealed, it prevents other classes from deriving from it, effectively sealing the class and disallowing any further inheritance.

Here are some key points regarding sealed classes in C#:

  1. Class Declaration:
    • A sealed class is declared using the sealed keyword before the class definition.
    • It is typically used as a modifier for a class that you do not want to be inherited.
  2. Inheritance Restriction:
    • Once a class is marked as sealed, it cannot serve as a base class for other classes.
    • Derived classes cannot be created, and attempts to derive from a sealed class will result in a compilation error.
  3. Preventing Method Overrides:
    • Sealing a class also prevents derived classes from overriding its virtual or abstract methods.
    • Methods declared as virtual in the sealed class cannot be overridden, and abstract methods cannot be implemented in derived classes.
  4. Sealed Methods:
    • In addition to sealing a class, individual methods within a class can also be marked as sealed.
    • Sealed methods prevent further overrides in derived classes, even if the derived class is not sealed.
  5. Purpose of Sealed Classes:
    • Sealing a class is useful when you want to prevent further extension or modification of the class’s behavior.
    • It can be used to ensure that the class’s implementation remains intact and cannot be overridden or altered by derived classes.
    • Sealed classes are often used when designing immutable classes or utility classes that should not be modified or extended.

Here’s an example demonstrating the usage of a sealed class:

public sealed class SealedClass
{
    // Class members and implementation
}

In this example, the 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.

It’s worth noting that not all classes need to be sealed. By default, classes in C# are inheritable, and they can be used as base classes for other classes. Sealing a class should be done deliberately and when there is a specific need to prevent inheritance or modification of the class’s behavior.

In summary, a sealed class in C# is a class that cannot be inherited or overridden. It prevents other classes from deriving from it and modifying its behavior. Sealing a class ensures the integrity and stability of its implementation, making it useful for scenarios where further extension or modification is not desired or allowed.

error: Content is protected !!