Home
Map
ArrayTypeMismatchExceptionUnderstand the ArrayTypeMismatchException type, which occurs when an invalid assignment is done.
C#
This page was last reviewed on Sep 11, 2023.
ArrayTypeMismatch Exception. The ArrayTypeMismatchException is thrown when an array element location is assigned to an object whose type is not compatible.
Array covariance. The term "array covariance" sounds complicated, and it is, but it relates to how arrays of different objects can be casted back and forth.
Exception
Example. 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.
Detail An error occurs when assigning an invalid type element, but because of the base 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 ...
Array notes. 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
A summary. 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.
C#VB.NETPythonGoJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 11, 2023 (edit).
Home
Changes
© 2007-2023 Sam Allen.