You don't.
In C# 2 and 3 it is impossible to have reference equality AND vary the element type.
In C# 4, you can have reference equality and vary the element type; such a conversion is called a "covariant" conversion. Covariant conversions will only be legal on IEnumerable<T>
, not on IList<T>
or List<T>
. Covariant conversions will only be legal when the source and target T types are reference types. In short:
List<Mammal> myMammals = whatever;
List<Animal> x0 = myMammals; // never legal
IEnumerable<Mammal> x1 = myMammals; // legal in C# 2, 3, 4
IEnumerable<Animal> x2 = myMammals; // legal in C# 4, not in C# 2 or 3
IEnumerable<Giraffe> x3 = myMammals; // never legal
IList<Mammal> x4 = myMammals; // legal in C# 2, 3, 4
IList<Animal> x5 = myMammals; // never legal
IList<Giraffe> x6 = myMammals; // never legal
List<int> myInts = whatever;
IEnumerable<int> x7 = myInts; // legal
IEnumerable<object> x8 = myInts; // never legal; int is not a reference type