Sunday, April 22, 2012

What is IEnumerable in .net?


It's an interface implemented by Collection types in .NET that provide the Iterator pattern. There also the generic version which is IEnumerable<T>.
The syntax (which you rarely see because there are prettier ways to do it) for moving through a collection that implements IEnumerable is:
 IEnumerator enumerator = collection.GetEnumerator();

while(enumerator.MoveNext())
{
    object obj = enumerator.Current;
    // work with the object
}
Which is functionaly equivalent to:
foreach(object obj in collection)
{
    // work with the object
}

If the collection supports indexers, you could also iterate over it with the classic for loop method but the Iterator pattern provides some nice extras like the ability to add synchronization for threading.

No comments:

Post a Comment