Mixing generics and polymorphism

Polymorphism, which attempts to hide differences in implementation, and generics, which attemtps to highlight them by providing exact information about types, don’t seem to mix very well. Consider the following fairly common pattern.

        class Base
{
}

class Derived : Base
{
}

abstract class Manipulator
{
List<Base> list;

public Manipulator(List<Base> list)
{
this.list = list;
}
}

class BaseManipulator : Manipulator
{
public BaseManipulator(List<Base> list)
: base(list)
{ }
}

class DerivedManipulator : Manipulator
{
public DerivedManipulator(List<Derived> list)
: base(list)
{ }
}

public static void Main()
{
List<Derived> list = new List<Derived>();
list.Add(new Derived());
DerivedManipulator d = new DerivedManipulator(list);
}


The code above will not compile – the compiler complains that List<Derived> cannot be converted to List<Base> in DerivedManipulator’s constructor. Which seems kindof strange, given that Derived[] is implicitly convertible to Base[]. But what would happen if implicit conversion occurred with generics?

List<Derived> derivedList = new List<Derived>();
List<Base> baseList = derivedList;
baseList.Add(new Base());
Derived d = derivedList[0]; // BOOM

All hell will break loose. The type safety that generics offer will disappear, obviating the very need for generics.


What can be done then? We could make Manipulator a generic class, taking the type of the List as a generic parameter and make DerivedManipulator derive from Manipulator<Derived>. But then we are only shifting the problem – treating Manipulators polymorphically becomes impossible then.


There seems to be a basic impedance mismatch between polymorphism and generics. Does anyone know of a better way to solve the problem?