Skip to content

Iteration

by Alex Peck on September 23rd, 2009

Iteration in .NET can be acomplished in two ways: indexing and using the IEnumerable interface. Indexing is an elementary programming concept covered elsewhere.

IEnumerable & IEnumerator

The IEnumerable interface would perhaps have been better named IForwardIteratable, since it defines a scheme for forward only iteration. IEnumerable specifies a single method, GetEnumerator, which returns an IEnumerator, the actual forward iterator. IEnumerator specifies three members:

  • Current property: the collection element to which the iterator is pointing.
  • MoveNext method: moves the iterator to the next element in the collection. Returns false when the iterator has passed the final element.
  • Reset method: set the iterator to the initial state, where calling MoveNext results in the iterator pointing at the first element.

You may then traverse a collection as follows:

IEnumerator enumerator = collection.GetEnumerator();
while (enumerator.MoveNext())
{
   Console.WriteLine(enumerator.Current.ToString());
}

foreach

The code snippet above might seem a little cumbersome. To improve matters both VB and C# provide the foreach language level construct. Using foreach the example above becomes simply:

foreach (object element in collection)
{
   Console.WriteLine(element.ToString());
}

Notice that this scheme is based on object rather than the derived type in the collection. So, if you don’t use generic collections, there might be an implicit cast from IEnumerator.Current to the target type.

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS