ENUMERATING THINGS WITH .NET

The basis of .NET collection types is an interface called IEnumerable. Newer classes (all those introduced since .NET 2.0) are based on the generic IEnumerable<T> instead, but for the purposes of this description, the untyped basic IEnumerable shall suffice. All collection classes implement IEnumerable, but sometimes classes that implement only this interface are called sequences instead of collections. As you will see, IEnumerable only requires extremely basic functionality. Here’s the interface declaration itself:

public interface IEnumerable {

  IEnumerator GetEnumerator( );

}

The only thing the interface IEnumerable actually allows you to do is to query another interface (IEnumerator) from a class. Here’s the declaration of IEnumerator:

public interface IEnumerator {

  object Current { get; }

  bool MoveNext( );

  void Reset( );

}

Imagine a list object that implements IEnumerable. When GetEnumerator is called, the object returns an implementation of IEnumerator. That implementation allows iteration over the elements of the list. Call Reset to get to the start, get to the object in the current position using the Current property, and then call MoveNext and evaluate its return value to see if there are more elements. Extremely simple, really, but very powerful.

As far as this description goes, the system sounds quite clean. Unfortunately the C# compiler muddies the waters a little bit by implementing some trickery, so that a class like the following ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.