When IEnumerator.Reset() method is called?
The IEnumerable and IEnumerator should generally be separate classes, and except in the case of enumerators that always return empty or always return the same item, the GetEnumerator method must always return a new instance of an IEnumerator.
There isn't much point to IEnumerator.Reset; for-each loops don't use it, and consumers of an IEnumerable/IEnumerator can't use it unless they know what the enumerable type is, in which case they could use the actual type rather than the interface.
Reset is redundant; so much so that it is a requirement in the language spec for iterator blocks to throw an exception on Reset. The correct thing to do is simply dispose and release the old iterator, and call GetEnumerator again. Or better: avoid having to read it twice, since not all data is repeatable.
Reset is not called by foreach
. Looking at your Main method in Reflector confirms this.
The .NET classes, like ArrayList
, actually return a new instance of a class that implements IEnumerator.
For example ArrayList
implements IEnumerable
, and its GetEnumerator
method looks like this:
public virtual IEnumerator GetEnumerator()
{
return new ArrayListEnumeratorSimple(this);
}
so there is no need to worry about calling Reset since every foreach uses a new instance of the enumerator.
For a complete example showing the implementation of IEnumerable and a separate class implementing IEnumerator, you can look at the documentation for IEnumerable.