-1

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!

ShubaShaba
  • 13
  • 3
  • 2
    "And why it doesn't crash ?" - it will (with a `NotImplementedException`) if you end up calling that. You haven't shown how you're using this at all. In general, I'm finding your question hard to understand - partly because you're asking four questions in a single post. Stack Overflow works much better if you ask *one* question per post. – Jon Skeet Apr 16 '21 at 20:56
  • I am not using it(empty main method). The aim is to get it runnable – ShubaShaba Apr 16 '21 at 21:11
  • I hope it is better now. – ShubaShaba Apr 16 '21 at 21:21

1 Answers1

2
  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.
greenjaed
  • 589
  • 8
  • 20