This article describes array covariance issues to which a Microsoft Visual Basic .NET or Microsoft Visual Basic 2005 application is vulnerable.
An array covariance occurs when the following conditions are true:
- You have two reference types. For example, you have class A and class B.
- The two reference types have an implicit or explicit reference conversion from a class of B to a class of A.
The same reference conversion issue exists from an array of B[
R] to an array of A[
R]. In this example,
R represents an element of an array.
Array covariance means that an element of an array that has an element type of A is actually an element of an array that has an element type of B if the following conditions are true:
- Both A and B are a reference type.
- A is a base type of B.
In the second invocation of the F method in the following code example, the actual element of the array variable b is B, not A. Therefore, the element is treated as a different class and a
System.ArrayTypeMismatchException exception is thrown.
Array covariance does not apply to an array of values.
The following Visual Basic .NET or Visual Basic 2005 code example demonstrates how the
System.ArrayTypeMismatchException exception is thrown when you run a console application.
Notice that function F takes a class A object as a parameter. However, function F actually receives a class B object. This behavior causes the
System.ArrayTypeMismatchException exception to be thrown at run time.
Module Module1
Class A
End Class
Class B
Inherits A
End Class
Sub Main()
Dim a() As A
ReDim a(10)
Dim b() As A = New B(10) {} ' An implicit reference conversion is performed.
F(a(0)) ' This works correctly.
F(b(0)) ' Because the element type of an array b is class B, an ArrayTypeMismatchException exception is thrown.
End Sub
Sub F(ByRef x As A)
End Sub
End ModuleFor more information about array covariance from the Visual Basic .NET language specification, visit the following Microsoft Developer Network (MSDN) Web site: