This question came to mind after reading the answer to this question; which basically made the point that List<T>
has no virtual methods, since it was designed to be "fast, not extensible".
If that's the design goal, why didn't the original design including sealing the class? (I know that's not possible now, seeing how that would break a lot child classes within client code)
It's not an access modifier, it's to do with whether a class can be inherited from or not...
Sealed class is used to stop a class to be inherited. You cannot derive or extend any class from it. Sealed method is implemented so that no other class can overthrow it and implement its own method.
By using sealed class, we can restrict access to the classes and its members with the help of a sealed keyword and we can also avoid inheriting the defined classes from other classes. In C#, a sealed class is a class that cannot be inherited by another class but it can be instantiated.
There's no compelling reason to seal it. It does no harm to derive from it. I used to be of the opposite mindset - only leave things unsealed that you intend for people to derive from. But in hindsight, it makes no sense. .NET takes the position that methods are non-virtual by default but classes are unsealed by default. List<T>
just follows that same practice.
Where you would want to seal a class is when it does override virtual methods but further subclassing is not easy or obvious. It can be slightly useful to derive from a collection such as Dictionary<TKey,TValue>
to stick in known type parameters and avoid typing them out if used in an application. For example maybe you would have a QueryString class that derives from Dictionary<String,String>
.
And since there's no virtual methods, there's really nothing to protect the class against by sealing it.
There must be many reasons why they decided not to make List<T>
sealed, however, one possibility is that the Framework design team wanted parity with ArrayList
(which is not sealed) so that existing programs and Frameworks which had designs based on extending ArrayList
would be able to more easily upgrade their designs to use List<T>
. Making List<T>
sealed would have been a real dead-end for these uses and one of the strong guiding design choices would have been to allow people to easily upgrade their existing code-bases from ArrayList
to List<T>
.
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