Covariant Arrays in .NET
Friday 10 May 2002
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
}
}
Posted by
at 07:59 AM.
Permalink.
Copyright © Charles Cook.
Valid XHTML 1.0