ArrayTypeMismatch
Exception
The ArrayTypeMismatchException
is thrown when an array element location is assigned to an object whose type is not compatible.
The term "array covariance" sounds complicated, and it is, but it relates to how arrays of different objects can be casted back and forth.
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.
class
type, the compiler cannot detect this.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; } }Unhandled Exception: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. at Program.Main() in ...
All string
types derive from object types. Therefore you can apply array covariance to treat the string[]
as an object[]
reference.
string
memory location, so the ArrayTypeMismatchException
is triggered.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.