I'd like to hear what is the motivation behind the bulk of sealed classes in the .Net framework. What is the benefit of sealing a class? I cannot fathom how not allowing inheritance can be useful and most likely not the only one fighting these classes.
So, why is the framework designed this way and wouldn't it be unbreaking change to unseal everything? There must be another reason than just being evil?
Marking a class as Sealed prevents tampering of important classes that can compromise security, or affect performance. Many times, sealing a class also makes sense when one is designing a utility class with fixed behaviour, which we don't want to change.
Techopedia Explains Sealed ClassA 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.
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.
Classes should either be designed for inheritance or prohibit it. There is a cost to designing for inheritance:
Item 17 of Effective Java goes into more details on this - regardless of the fact that it's written in the context of Java, the advice applies to .NET as well.
Personally I wish classes were sealed by default in .NET.
The MSDN article for this topic is Limiting Extensibility by Sealing Classes.
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