In C# and C++/CLI the keyword sealed
(or NotInheritable
in VB) is used to protect a class from any inheritance chance (the class will be non-inheritable). I know that one feature of object-oriented programming is inheritance and I feel that the use of sealed
goes against this feature, it stops inheritance. Is there an example that shows the benefit of sealed
and when it is important to use it?
Sealed Classes allow us to fix type hierarchies and forbid developers from creating new subclasses. They are useful when we have a very strict inheritance hierarchy, with a specific set of possible subclasses and no others.
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.
We use sealed classes to prevent inheritance. As we cannot inherit from a sealed class, the methods in the sealed class cannot be manipulated from other classes. It helps to prevent security issues.
Set your class to seal when it needs to be sealed and private when it needs to be private. Don't make them sealed by default. Show activity on this post. I find that sealed / final classes are actually pretty rare, in my experience; I would certainly not recommend suggesting all classes be sealed / final by default.
On a class that implements security features, so that the original object cannot be "impersonated".
More generally, I recently exchanged with a person at Microsoft, who told me they tried to limit the inheritance to the places where it really made full sense, because it becomes expensive performance-wise if left untreated.
The sealed keyword tells the CLR that there is no class further down to look for methods, and that speeds things up.
In most performance-enhancing tools on the market nowadays, you will find a checkbox that will seal all your classes that aren't inherited.
Be careful though, because if you want to allow plugins or assembly discovery through MEF, you will run into problems.
An addendum to Louis Kottmann's excellent answer:
On a related note, applicable to unsealed classes only: any method created virtual
is an extension point, or at least looks like it should be an extension point. Declaring methods virtual
should be a conscious decision as well. (In C# this is a conscious decision; in Java it isn't.)
And then there's this:
Some relevant links:
Also note that Kotlin seals classes by default; its open
keyword is the opposite of Java's final
or the sealed
of C#. (To be sure, there is no universal agreement that this is a good thing.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With