Thursday, February 23, 2006 - Posts

C# and Java Generics .... Covariance ....

The Java case:


The C# case:


Painful - but generics are not covariant in either case - meaning ....

(Java - from above link)
    List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li; // illegal

(C# from above link)

    // create new List<Base>
List<Base> baseArray = new List<Base>();

// create new List<Derived>
List<Derived> derivedArray = new List<Derived>();

// CANNOT assign List<Derived> to List<Base>

List<Base> baseArray2 = derivedArray; // compiler error here


I am getting into using generics for non-trivial circumstances now. I am implementing generic classes - not just using the List<T> stuff anymore. Now that I am getting down to it - as always - it is an art :)