Array Covariance
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

Array Covariance

Given reference class D with direct or indirect base class B, an array of type D can be assigned to an array variable of type B.

// clr_array_covariance.cpp
// compile with: /clr
using namespace System;

int main() {
   // String derives from Object
   array<Object^>^ oa = gcnew array<String^>(20);

An assignment to an array element shall be assignment-compatible with the dynamic type of the array. An assignment to an array element with incompatible type will cause System::ArrayTypeMismatchException to be thrown.

Array covariance does not apply to arrays of value class type. For example, arrays of Int32 cannot be converted to Object^ arrays, even via boxing.

// clr_array_covariance2.cpp
// compile with: /clr
using namespace System;

ref struct Base { int i; };
ref struct Derived  : Base {};
ref struct Derived2 : Base {};
ref struct Derived3 : Derived {};
ref struct Other { short s; };

int main() {
   // Derived* d[] = new Derived*[100];
   array<Derived^> ^ d = gcnew array<Derived^>(100);

   // ok by array covariance
   array<Base ^> ^  b = d;

   // invalid
   // b[0] = new Other;

   // error (runtime exception)
   // b[1] = gcnew Derived2;

   // error (runtime exception),
   // must be "at least" a Derived.
   // b[0] = gcnew Base;

   b[1] = gcnew Derived;
   b[0] = gcnew Derived3;
© 2015 Microsoft