O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required