Microsoft KB Archive/896579

= Your Visual Basic .NET or Visual Basic 2005 application may be vulnerable to array covariance issues =

Article ID: 896579

Article Last Modified on 12/3/2007

-

APPLIES TO


 * Microsoft .NET Framework 2.0
 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework 1.0
 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-







For a Microsoft Visual C# .NET version of this article, see 897545.



SUMMARY
This article describes array covariance issues to which a Microsoft Visual Basic .NET or Microsoft Visual Basic 2005 application is vulnerable.



MORE INFORMATION
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[ ] to an array of A[ ]. In this example,  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 Module

