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

IMPLEMENTING ITERATOR FUNCTIONS

C#’s iterator feature, introduced in C# version 2.0, allows you to create implementations of the IEnumerable/IEnumerator combination without ever implementing either of those interfaces manually. It goes even farther by supporting the generic interfaces in addition to the non-generic ones, and making it possible to implement IEnumerator only.

Typically, it is only necessary to implement a function with a particular return type to use this feature. The second criterion the compiler looks for in order to apply its transformations (more about that in a moment) is the use of at least one of several special keywords within that function. Most common is the yield return statement. For example, the earlier EndlessList example can be implemented as a C# iterator like this (using a generic interface for a change):

public static IEnumerable<int> EndlessListFunction( ) {

  int val = 0;

  while (true)

    yield return val++;

}

To understand how to work with this, it’s easiest to take it literally. The return type of the function is an IEnumerable<int>, so you use it in the same places where you might otherwise use a class instance that implements this interface. Here’s some code that iterates through the EndlessListFunction sequence:

var list = EndlessListFunction( );

foreach (var item in list)

  Console.WriteLine(item);

The C# compiler automatically creates a class that implements the interface IEnumerable<int>. The logic of that class and the corresponding ...

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