C# ArrayTypeMismatch Exception

The ArrayTypeMismatchException is thrown in a certain program context. It is thrown when an array element location is assigned to an object whose type is not compatible. It is related to the array covariance rules.

Error dialog screenshot: stopped working

Example

Note

We show how the ArrayTypeMismatchException is thrown. The .NET Framework supports array covariance and contravariance. These are ways to treat an array of a more derived type as an array of the less derived base class type.

The runtime must perform type checks on array elements when you assign to them. Then, an exception is thrown to indicate that an array element is being assigned an object of invalid type.

Usually:An error occurs when assigning an invalid type element, but because of the base class type, the compiler cannot detect this.

C# program that throws array mismatch exception

class Program
{
    static void Main()
    {
	// Declares and assigns a string array.
	// ... Then implicitly casts to base class object.
	// ... Then assigns invalid element.
	string[] array1 = { "cat", "dog", "fish" };
	object[] array2 = array1;
	array2[0] = 5;
    }
}

Output

Unhandled Exception: System.ArrayTypeMismatchException:
Attempted to access an element as a type incompatible with the array.
   at Program.Main() in ...
Main method

This program introduces the Program class and the Main entry point method. The first statement uses the array initializer syntax form to assign three string literals to the array data on the managed heap.

Array InitializersObject keyword

Next the string array is treated as an object array. This is possible because all string types derive from object types. Therefore you can apply array covariance to treat the string[] as an object[] reference.

But:You cannot physically put an integer in a string memory location, so the ArrayTypeMismatchException is triggered.

String ArrayObject Array

Summary

We looked at the ArrayTypeMismatchException in the .NET Framework. This exception is a result of the array covariance rules. The string type is derived from the object type and we can therefore use a string array as an object array type.

And:At this point, the compile-time checking cannot provide type checks for us.

Then:The assignment of an integer to a string memory location throws this exception.

Array.ConstrainedCopy

C#: Exception