Search code examples
c#genericsienumerableienumerator

GetEnumerator realization within generic class


I have a custom array class public class CustomArray<T> : IEnumerable<T> with a generic property:

public T[] Array
{
    get;
}

How can I implement a GetEnumerator? What i have right now:

public IEnumerator<T> GetEnumerator()
{
    return (IEnumerator<T>)Array.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
    return Array.GetEnumerator();
}

But the first one does not pass the Unit test.
Result Message:

System.InvalidCastException : Unable to cast object of type 'System.SZArrayEnumerator' to type 'System.Collections.Generic.IEnumerator`1[System.Int32]'.


Solution

  • There is both IEnumerable.GetEnumerator() and IEnumerabl<T>.GetEnumerator() with the same signature, which would clash if they were declared normally.

    Therefore, generally the former is added directly (being the older interface) and the latter is added as an explicit interface implementation, which can only be accessed by explicitly casting:

    public IEnumerator<T> GetEnumerator()
    {
        return ((IEnumerable<T>)Array).GetEnumerator();
    }
    

    Side note:

    Single-dimension arrays don't actually implement any interfaces directly anyway. This is because all the code that resides in the Array class has no knowledge of types or dimensions, and cannot access the array with static typing.

    So a class called SZArrayHelper implements all the interfaces, and the CLR is coded to use trickery to get the arrays to cast as if they were actually that type.