Last Updated: May 24, 2023
·
6.289K
· teddy

C# ArrayTypeMismatchException

An array mismatch exception occurs when an incompatible data type is added to an array. This can be seen both at compile time and run-time.

Compile-time errors are easy to see, this occurs because an int does not have a base class of string.

Code to generate compile-time error:

string[] test = new string[] { "a" };
test[0] = 2;

Run-time errors are a little more cryptic. This error is not caught during compile because the base class is not violated. Strings can be cast as objects since they inherit from Object. However, an Object cannot be placed back into the array after the split. Split returns a string array, and implicitly casts the object array as a string array. Since String is a derived class, the new object() call causes a mismatch error, as object() does not have a base class of String. Even an explicit cast cannot save us.

To work-around this error, I individually assign the string to each element of the object array. The types are not violated as String is a derivative of Object.

public class Array_Mismatch
{
    public static void arrayMismatchTest()
    {
        createMismatchError();          //String[], Attempted to access an element as a type incompatible with the array.

        createWorkAround();             //Object[], System.Object can be added to the array.
    }

    private static void createMismatchError()
    {
        string type = string.Empty;

        try
        {
            //instantiate an object[], but pass into it string[]
            object[] array = (object[])("here|comes|an|error".Split('|'));

            //get the type to show the implicit conversion
            type = array.GetType().Name;

            //attempt to replace the first element with an object
            array[0] = new object();

            //print the array (this will not print due to ArrayTypeMismatchError)
            Console.WriteLine(string.Format("{0}, {1}", type, string.Join(" ", array)));
        }
        catch (ArrayTypeMismatchException ex)
        {
            //this will fire, as the object array has been implicitly cast as a string array by the split return
            Console.WriteLine(ex.Message);
        }
    }

    private static void createWorkAround()
    {
        string type = string.Empty;

        try
        {
            //split the string array
            string[] split = "???|can|be|added|to|the|array.".Split('|');

            //instantiate an object[]
            object[] array = new object[split.Length];

            //iterate over the split array adding to the object array
            for (int i = 0; i < split.Length; i++)
                array[i] = split[i];

            //get the type to show no conversion
            type = array.GetType().Name;

            //assign a new object to the array at the first element
            array[0] = new object();

            //print the array (this will not print due to ArrayTypeMismatchError)
            Console.WriteLine(string.Format("{0}, {1}", type, string.Join(" ", array)));
        }
        catch (ArrayTypeMismatchException ex)
        {
            //this will not fire
            Console.WriteLine(ex.Message);
        }
    }
}

Further reading:
Eric Lippert on covariance and object compatibility

1 Response
Add your response

thank you very much for posting!

11 months ago ·