Microsoft KB Archive/897545

= Your Visual C# .NET application may be vulnerable to array covariance issues =

Article ID: 897545

Article Last Modified on 5/18/2007

-

APPLIES TO


 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework 1.0
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-







For a Microsoft Visual Basic .NET version of this article, see 896579.



SUMMARY
This article describes array covariance issues to which a Microsoft Visual C# .NET 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 C# .NET 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. class A {}

class B : A {}

class Class1 {   static void Main {       A[] a = new A[10]; A[] b = new B[10]; // An implicit reference conversion is performed. F(ref a[0]); // This works correctly. F(ref b[0]); // Because the element type of an array b is class B, an ArrayTypeMismatchException exception is thrown. }

static void F(ref A x){} }

