Information Technology Reference
In-Depth Information
Array Covariance
Under certain conditions, you can assign an object to an array element even if the object is not
of the array's base type. This property is called covariance . You can use covariance if
￿
The array is a reference type array.
￿
There is an implicit or explicit conversion between the type of the object you are assign-
ing and the array's base type.
Since there is always an implicit conversion between a derived class and its base class, you
can always assign an object of a derived class to an array declared for the base class.
For example, the following code declares two classes, A and B , where class B derives from
class A . The last line shows covariance by assigning objects of type B to array elements of type
A . The memory layout for the code is shown in Figure 14-15.
class A { ... } // Base class
class B : A { ... } // Derived class
class Program {
static void Main() {
// Two arrays of type A[]
A[] AArray1 = new A[3];
A[] AArray2 = new A[3];
// Normal--assigning objects of type A to an array of type A
AArray1[0] = new A(); AArray1[1] = new A(); AArray1[2] = new A();
// Covariant--assigning objects of type B to an array of type A
AArray2[0] = new B(); AArray2[1] = new B(); AArray2[2] = new B();
}
}
Figure 14-15. Arrays showing covariance
Note There is no covariance for value type arrays.
Search WWH ::




Custom Search