Search code examples
c#.netlanguage-designsealed

Why isn't List<T> sealed?


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)


Solution

  • 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.