Cover by Oliver Sturm

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required