Export (0) Print
Expand All

4.5.6 Array Covariance

Visual Studio .NET 2003

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

Example

// __gc_arrays8.cpp
// compile with: /clr
#using <mscorlib.dll>
using namespace System;

int main() {
   Object* oa[] = new String*[20];  // String derives from Object
}

Constraint

  • 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.

    Example

    // __gc_arrays9.cpp
    // compile with: /clr
    #using <mscorlib.dll>
    using namespace System;
    
    __gc struct Base { int i; };
    __gc struct Derived  : Base {};
    __gc struct Derived2 : Base {};
    __gc struct Derived3 : Derived {};
    __gc struct Other { short s; };
    
    int main() {
       Derived* d[] = new Derived*[100];
    
       // ok by array covariance
       Base*   b[] = d;
    
       // invalid
       // b[0] = new Other;
    
       // error (runtime exception)
       // b[1] = new Derived2;
    
       // error (runtime exception),
       // must be "at least" a Derived.
       // b[0] = new Base;      
                             
       b[1] = new Derived;
       b[0] = new Derived3;
    }
    

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

Show:
© 2014 Microsoft