Search code examples
c#interfaceienumerable

Why not "IEnumerator IEnumerator.GetEnumerator()" while declaring the interface method ? IEnumerable interface


I have 3 questions about IEnumerable<T> and IEnumerator<T> interface:

  1. Why not IEnumerator IEnumerator.GetEnumerator(), since it is the interface method ?

  2. Why it could not be public ?

  3. Why the returning value Current supposed to be an object, even if I know the specific type ?

the code: (the questions are marked)

 public class myIEnumCollection : IEnumerable<int> 
        {
            public IEnumerator GetEnumerator() // 1)
            {
                return new myIEnumerator();           
            }

            IEnumerator<int> IEnumerable<int>.GetEnumerator(){ // 2)  
                throw new NotImplementedException();
            }
        }

        public class myIEnumerator: IEnumerator<int> {

            public int Current{get; private set; } = 0;
            object IEnumerator.Current => Current; // 3)

            public bool MoveNext(){ 
                Current++;    
                return true; 
            }
            public void Reset() {
                Current = 0;
            } 

            public void Dispose(){

            }
        }

Thank you!


Solution

    1. I think you have your implementations reversed. If you follow the sample code on IEnumerable<T>'s page, you would declare it like this:
    public IEnumerator<int> GetEnumerator()
    {
        return new myIEnumerator();
    }
    
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
    
    1. IEnumerable<T> implements the non-generic interface IEnumerable and both define a method GetEnumerable() with different return types. Because of this, only one of these methods can be directly accessed (see this question for more information: C# Interfaces. Implicit implementation versus Explicit implementation)
    2. Related to 2, IEnumerator<T> implements the non-generic interface IEnumerator which defines it as an object.