Why not always use Generics?

Generics may be fast and type safe, but also add complexity (another dimension which can vary and must be understood by programmers). Who is going to maintain your code? Not every trick with generics (or lambdas, or dependency injection, or...) is worth it. Think about what problem you are going to solve, and what parts of that problem may change in the future. Design for those cases. The optimally flexible software is too complex to be maintained by mortal programmers.


In general you should - however, there are times (especially when writing library code) when it is not possible (or certainly not convenient) to know about the calling type (even in terms of T), so non-generic types (mainly interfaces such as IList, IEnumerable) are very useful. Data-binding is a good example of this. Indeed, anything that involves reflection is generally made much harder by using generics, and since (via the nature of reflection) you've already lost those benefits, you may as well just drop to non-generic code. Reflection and generics are not very good friends at all.


Sometimes "object" collections are simply unavoidable. Often this happens when there's multiple types in the same control/collection - the only type they have in common is "object", and so that's the best type for your collection.

Another case for object (non collection related) that pops up from time to time can be seen with the PropertyGrid. A third party property grid may allow you to attach a "validator" which returns whether the users new value for a given property on the grid is acceptable. As the PropertyGrid does not know what properties it will be displaying, the best it can give the validator is an object - even though the validator knows exactly what type it will be called with.

But as per Mark's answer - most (all?) of the non generic collections in .NET are only there for legacy reasons. If .NET was remade today you can be sure the standard library would look very different.

Tags:

.Net

Generics