Export (0) Print
Expand All

8.5 Array Covariance

Visual Studio .NET 2003

For any two reference types A and B, if A is a derived type of B, a conversion exists from an array of type A to a compatible array of type B. A compatible array is an array of the same rank and type. This relationship is known as array covariance. Array covariance in particular means that an element of an array whose element type is B may actually be an element of an array whose element type is A, provided that both A and B are reference types and that B is a base type of A. In the following example, the second invocation of F causes a System.ArrayTypeMismatchException exception to be thrown because the actual element type of b is String, not Object:

Module Test
    Sub F(ByRef x As Object)
    End Sub

    Sub Main()
        Dim a(10) As Object
        Dim b() As Object = New String(10) {}
        F(a(0)) ' OK.
        F(b(1)) ' Not allowed: System.ArrayTypeMismatchException.
   End Sub
End Module

Because of array covariance, assignments to elements of reference type arrays include a run-time check that ensures that the value being assigned to the array element is actually of a permitted type.

Module Test
    Sub Fill(array() As Object, index As Integer, count As Integer, _
            value As Object)
        Dim i As Integer

        For i = index To (index + count) – 1
            array(i) = value
        Next i
    End Sub

    Sub Main()
        Dim strings(100) As String

        Fill(strings, 0, 101, "Undefined")
        Fill(strings, 0, 10, Nothing)
        Fill(strings, 91, 10, 0)
    End Sub
End Module

In this example, the assignment to array(i) in method Fill implicitly includes a run-time check that ensures that the object referenced by the variable value is either Nothing or an instance of a type that is compatible with the actual element type of array array. In method Main, the first two invocations of method Fill succeed, but the third invocation causes a System.ArrayTypeMismatchException exception to be thrown upon executing the first assignment to array(i). The exception occurs because an Integer cannot be stored in a String array.

Array covariance specifically does not extend to arrays of value types.

See Also

8.5 Array Covariance | 8.8 Widening Conversions | 8.9 Narrowing Conversions | 8. Conversions | Conversion Summary (Visual Basic Language Reference) | Array Conversions (Visual Basic Language Concepts)

Show:
© 2015 Microsoft