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)


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

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.