C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 ...
But: You cannot physically put an integer in a string memory location, so the ArrayTypeMismatchException is triggered.
Object ArrayAnd: 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.Copy