C# ArrayTypeMismatchException

Understand the ArrayTypeMismatchException type, which occurs when an invalid assignment is done.

dot net perls

ArrayTypeMismatch Exception. The ArrayTypeMismatchException is thrown in a certain situation. 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.Exception

Example. 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.
Info: 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 ...

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.Initialize Array

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.
Object 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.


© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.