Inheritance is one of the pillars of object-oriented programming. But what if you donโt want your class to be inherited? Maybe itโs core logic that shouldnโt be changed or a utility that needs to stay stable.
C# makes this easy with the sealed keyword.
What is a sealed Class?
A sealed class is a class that cannot be used as a base class. It stops other developers (and yourself) from creating a subclass and potentially altering or extending its behavior.
Example:
What-is-a-sealed-Class
What Does a Sealed Class Offer?
Sealing a class isnโt just about stopping inheritance but reinforcing good software design.
- Security โ Prevents unintended modifications, making your codebase more secure and predictable.
- Performance โ Enables the compiler to apply advanced optimizations by avoiding virtual method dispatch.
- Design Intent โ Communicates that the class is not meant to be extended or modified.
**
When should you use a sealed class?**
- Utility Classes โ If your class acts like a helper or static service, sealing it prevents unnecessary or harmful subclassing.
- Immutable Classes โ Sealing enforces immutability, ensuring no one can override behavior or add mutable state.
- Framework Design โ In library or API development, sealing ensures consumers of your code use it as intended, maintaining strict control over extensibility.
Conclusion
The sealed keyword in C# may seem small, but its impact on code quality, performance, and design clarity is significant. Whether building a secure utility, enforcing immutability, or designing a stable API, sealing your classes can help you write cleaner, more maintainable code.