I assume the following sample gives a best practice that we should follow when we implement the IEnumerable interface.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenext
Here is the question:
- Why should we provide two version of Current method?
- When the version ONE (object IEnumerator.Current) is used?
- When the version TWO (public Person Current ) is used?
- How to use PeopleEnum in the foreach statement. // updated
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
// explicit interface implementation
object IEnumerator.Current /// **version ONE**
{
get
{
return Current;
}
}
public Person Current /// **version TWO**
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
I suspect the reason is that this code example was derived from an example class implementing
IEnumerator<T>– if the example classPeopleEnumimplementedIEnumerator<T>this approach would be required:IEnumerator<T>inheritsIEnumeratorso you have to implement both interfaces when implementingIEnumerator<T>.The implementation of the non-generic
IEnumeratorrequiresCurrentto return object – the strongly typedIEnumerator<T>on the other hand requires Current to return an instance of typeT– using explicit and direct interface implementation is the only way to fulfill both requirements.