Your Visual C# .NET application may be vulnerable to array covariance issues (897545)



The information in this article applies to:

  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0
  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)

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[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 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){}
}

REFERENCES

For more information about array covariance from the Visual C# .NET language specification, visit the following Microsoft Developer Network (MSDN) Web site:

Modification Type:MajorLast Reviewed:4/7/2005
Keywords:ArrayTypeMismatchException kbinfo kbhowto KB897545 kbAudDeveloper