Saturday, May 31, 2008

IEnumerable vs IEnumerator

IEnumerator<T> generic interface defines "cursor" methods for iterating over a collection:
T Current { get; }
bool MoveNext();
void Reset();
void Dispose();

IEnumerable<T> generic interface defines just one method:
IEnumerator<T> GetEnumerator();

C# supports iterator blocks. These are blocks of code (i.e. method or property getter blocks) in which you "yield" a return value at various points in the code. The compiler uses hidden magic to create a nested type that implements both IEnumerable<T> and IEnumerator<T>; the body of your original method is stubbed out to call into this new object, and all your original logic is implemented in the IEnumerator<T>'s MoveNext method.

The C# foreach keyword is quite flexible and operates on any object that exposes a public GetEnumerator() method (the 'collection' pattern) - the object doesn't have to implement IEnumerable or IEnumerable<T>.

No comments: