What Does Sealed Class Mean?
A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated.
The design intent of a sealed class is to indicate that the class is specialized and there is no need to extend it to provide any additional functionality through inheritance to override its behavior. A sealed class is often used to encapsulate a logic that needs to be used across the program but without any alteration to it.
A sealed class is mostly used for security reasons by preventing unintended derivation by which the derived class may corrupt the implementation provided in the sealed class. As the sealed class cannot form a base class, calls to sealed classes are slightly faster because they enable certain runtime optimizations such as invocation of virtual member functions on instances of sealed class into non-virtual invocations. Sealed class helps in versioning by not breaking compatibility while changing a class from sealed type to unsealed.
Some of the key classes in the .NET framework library are designed as sealed classes, mainly to limit the extensibility of these classes.
Techopedia Explains Sealed Class
Unlike a struct, which is implicitly sealed, a sealed class is declared with the keyword, “sealed” to prevent accidental inheritance of the class. A sealed class can be useful only if it has methods with public-level accessibility. A sealed class cannot be an abstract class as the abstract class is intended to be derived by another class that provides implementation for the abstract methods and properties.
For example, a sealed class, DatabaseHelper, can be designed with properties and methods that can service the functionalities of database-related actions, including open- and closed-database connection, fetch and update data, etc. Because it performs crucial functions that should not be tampered with by overriding in its derived classes, it can be designed as sealed class.
Sealing restricts the benefit of extensibility and prevents customization of library types. Hence, a class has to be sealed after carefully weighing the impact of sealing it. The list of criteria to consider for sealing a class includes:
- The class is static
- The class contains inherited members that represent sensitive information
- The class is queried to retrieve its attributes through the reflection method
- The class inherits many virtual members that need to be sealed