1

While implementing my own collection, I mocked the enumerator by coping all objects into a List, then redirect all enumerator calls to the list's enumerator, to which I stored a reference. But I ran into a problem when List.Enumerator doesn't have a Reset method; despite the fact that it implements IEnumerator.

Here are the reflected headers in question (with comments stripped)

    public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
    {
        public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
        {
            public T Current { get; }
            public void Dispose();
            public bool MoveNext();
        }
    }
    public interface IEnumerator<out T> : IDisposable, IEnumerator
    {
        T Current { get; }
    }
    public interface IEnumerator
    {
        object Current { get; }
        bool MoveNext();
        void Reset();
    }

Where we can see the List.Enumerator derives from IEnumerator twice; first explicitly, then implicitly through IEnumerator. But this sample program won't compile.

List<int> list = new List<int>();
List<int>.Enumerator enumerator = list.GetEnumerator();
enumerator.Reset();

Error CS1061 'List.Enumerator' does not contain a definition for 'Reset' and no extension method 'Reset' accepting a first argument of type 'List.Enumerator' could be found (are you missing a using directive or an assembly reference?)

How is it possible that List.Enumerator doesn't implement/expose a method declared in one of its interfaces?

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
AdIch
  • 111
  • 5

1 Answers1

0

The Reset method is implemented via explicit interface implementation. See: https://source.dot.net/#System.Private.CoreLib/shared/System/Collections/Generic/List.cs,1141

Therefore, it's not a public member of List<T>.Enumerator

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445