November 11, 2008

IEnumerable, IEnumerator and foreach Implementation

IEnumerable - Provides an IEnumerator that can traverse a collection

public IEnumerator GetEnumerator();

IEnumerator - Methods to traverse a collection

public object Current;
public bool MoveNext();
// Ignore the next method, it should be marked as [Obsolete], just use GetIterator()
public void Reset(); 

This code shows in a simplistic manner how foreach is implemented using iterators. See here for more details

// foreach Implementation
IEnumerable enumerable = (IEnumerable)targObject;
IEnumerator it = enumerable.GetEnumerator();
while(it.MoveNext())
{
    DoSomething(it.Current);
}

No comments: