I have 3 questions about IEnumerable<T>
and IEnumerator<T>
interface:
Why not IEnumerator IEnumerator.GetEnumerator()
, since it is the interface method ?
Why it could not be public ?
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!
IEnumerable<T>
's page, you would declare it like this:public IEnumerator<int> GetEnumerator()
{
return new myIEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
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)IEnumerator<T>
implements the non-generic interface IEnumerator
which defines it as an object.