Thursday, December 18, 2003 10:30 AM
richard
C# Arrays: Covariant Arrays
I am reading the annotated CLI standard currently and I recently read an interesting part about how Java influenced the decision to allow covariant arrays in C# / .NET. The example given was simiar to this:
using System;
class Program
{
static void Main(string[] args)
{
BaseType[] array = new Derived[10];
ModifyArray(array);
}
static void ModifyArray(BaseType[] array)
{
array[0] = new Derived();
array[1] = new BaseType();
}
}
class BaseType {}
class Derived : BaseType {}
The above code compiles without issue. However this same code throws an exception on the line array[1] = new BaseType();. This is because BaseType is simply not a Derived type: you can't downcast a BaseType to a Derived type. So covariance allows you to obtain a reference to an array where the reference is an upcast of the actual array type, but the actual underlying type is a specialization of the base type, thus completely precluding the base type or any other derived type from being added to that array. The annotator notes that this was a hotly debated design point and that Java was an influence in allowing covariant arrays in C#