Home > Mobile >  Does C# Compiler Treat Array Element Differently From The Same Type Variable?! (System.ArrayTypeMism
Does C# Compiler Treat Array Element Differently From The Same Type Variable?! (System.ArrayTypeMism

Time:12-14

I was working on something today, but I noticed something in the code, so let me explain the situation.

I get data as IEnumerable from different concreate classes of interface, look at this sample code

public interface ISampleClass {
    IEnumerable<ISampleClass> GetSampleData();
}

public class SampleClassAsPerson : ISampleClass
{
    public IEnumerable<ISampleClass> GetSampleData()
    {
        // Return data from DB
        // Return list for this example
        return new List<SampleClassAsPerson>() {new SampleClassAsPerson(), new SampleClassAsPerson()};
    }
}

I put the data that comes from GetSampleData() method in Array of my Interface(will see this in the code bellow), I noticed that my Array not holding the same data as the variable from the same type, lets look at the code

public class TestArrayAndSingle
{
    public const byte ARRAY_SIZE = 10;
    public const byte FIRST_PLACE_IN_ARRAY = 0;

    public static void DoTheTest()
    {
        // First as single element
        IEnumerable<ISampleClass> singleIEnumerable = new List<ISampleClass>();
        singleIEnumerable = new SampleClassAsPerson().GetSampleData(); // Works Fine for variable of type new List<ISampleClass>()


        // Second as array of elements 
        IEnumerable<ISampleClass>[] arrayOfIEnumerable = new IEnumerable<ISampleClass>[ARRAY_SIZE];
        arrayOfIEnumerable[FIRST_PLACE_IN_ARRAY] = new SampleClassAsPerson().GetSampleData(); // Works fine also


        IEnumerable<ISampleClass>[] arrayOfList = new List<ISampleClass>[ARRAY_SIZE];
        arrayOfList[FIRST_PLACE_IN_ARRAY] = new SampleClassAsPerson().GetSampleData(); // Return ArrayTypeMismatchException, This should be the same as singleIEnumerable I guess(new List<ISampleClass>())
    }
}

So for the first one IEnumerable singleIEnumerable = new List(); works fine but in IEnumerable[] arrayOfList = new List[ARRAY_SIZE]; first item gives exception (System.ArrayTypeMismatchException - Attempted to access an element as a type incompatible with the array.).

Can anyone explain why? does element in array treated differently from same type variable?!

CodePudding user response:

You have a collection of List<T> and are trying to store a more generic IEnumerable<T> in it. but not all IEnumerable<T>s are lists, so the compiler doesn't allow it. What if the IEnumerable<T> was a stack? or a linked list? or a LINQ query?

With a array of a certain type, you can store items that are of that type or more specific, but not less specific. So you can store lists in an array of enumerables (because all lists are enumerables), but not enumerables in an array of lists (since not all enumerables are lists).

  • Related