Cook Computing

Covariant Arrays in .NET

May 10, 2002 Written by Charles Cook

Covariant arrays. If B is a sub-type of A, then B[] is a sub-type of A[]. I've used them in .NET without being aware of the concept. They are frowned upon in some circles because their usage cannot be made statically type-safe. Instead, a runtime type check is required when writing to the array. For example, the following sample results in an ArrayTypeMismatchException being thrown.

class A {}
class B : A {}

class _
  static void Main()
    B[] bArray = new B[] { new B(), new B() };
    A[] aArray = bArray;
    aArray[0] = new A();  // runtime error