Generics vs. Polymorphism

Generics provide you with some good alternatives to solving the kinds of problems traditional polymorphism allows you to address. Unfortunately, generics alone can't replace polymorphism completely. The best solution is to have the two working together side by side in your code. The problem is that a generic class doesn't derive from the template class—so, for example, List<Banana> and List <Orange> don't have anything in common. Even if Banana and Orange both derive from Fruit, List<Banana> and List<Orange> don't share a common base with List<Fruit>. This is a limitation of template design.

You can navigate around this problem to some extent. However, polymorphism statements such as this one won't work:

If TypeOf( myLsitOfBananas) Is _
   List(Of Fruit) Then

Your code can take advantage of the generic template and type parameter only if you use Reflection to get the template and the type parameters, then compare the type parameters, and so on. The result is ugly and complex code that defeats the benefits of generics for the most part.

However, the situation improves if you use generics and traditional polymorphism side by side. For example, if you implement System.Collections.Generic.IList<T>, you can also implement System.Collections.IList. This lets you test easily to see if the object is an IList. An added benefit is that your code will probably work better with existing applications.

I expect that language tools and the .NET runtime will provide better ways to deal with this issue in the future. Until then, if you're a template designer, try to ensure you provide polymorphic interfaces as well as generic ones.