Resolved- Attempted to access an element as type incompatible with the array

Today in this article, we will cover below aspects,

Issue Description

C# application gives runtime error as below,

ArrayTypeMismatchException: “Attempted to access an element as a type incompatible with the array.”

Resolution

This error is a common error in numerous use cases and scenarios when developers are attempting to use BaseType and Derives type, not in accordance with the Covariance and Contravariant rules. NET.

Covariant and Contravariant generic type parameters provide flexibility in assigning and using the types. For example, covariant type parameters enable you to make assignments that look are like ordinary polymorphism.

Covariance enables you to use more derived types whereas Contravariance allows using more generic types.

Let’s take a simple example in understanding this error, which could also help you replicate the issue if you are facing the same error.

Array are covariant in .NET,

            String[] objString = new String[1];
            // objString  is an array of Object
            Object[] objTest = objString;

            // Assign an Integer to objTest . 
            objTest[0] = 12345;

  • In the above example, the array objString is an array of string,
  • The first assignment of array elements is valid because object ≥ string and
  • The second assignment is invalid because int ≤ object.
  • Above produces the error “Attempted to access an element as a type incompatible with the array”.

Type check verifies the runtime type of the definition of the elements of the array is greater or equal to the instance being assigned to the element.

So you should check and verify what type of array fields we are assigning to the target object. Covariance enables only to use of more derived types and hence application works fine at compile-time and runtime. But vice versa your application will give the error.

So any assignment you want to do should be done in accordance with the Covariance rule.

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *