Saturday, November 06, 2010

.Net–The difference between IEnumerable and IEnumerator

The easiest way to think about these 2 interfaces:

An object that is enumerable will provide an enumerator that allows you to enumerate over that object – Kapish?!

The interface IEnumerable defines one method: GetEnumerator that returns an object that implements IEnumerator. IEnumerator defines methods such as Current, MoveNext and Reset. Typically an object that implements IEnumerable, does so because it contains a list of data-items. Calling GetEnumerator on that object then provides us with an object that manages the iteration over the list of items contained on that object.

In terms of the “Gang of Four” patterns, IEnumerable and IEnumerator implement the iterator pattern and IEnumerable is the Aggregate and IEnumerator is the Iterator.

No comments: