Share via


Iterators (C# Programming Guide)

An iterator is a method, get accessor, or operator that performs a custom iteration over an array or collection class by using the yield keyword. The yield return statement causes an element in the source sequence to be returned immediately to the caller before the next element in the source sequence is accessed. Although you write an iterator as a method, the compiler translates it into a nested class that is, in effect, a state machine. This class keeps track of the position of the iterator as long the foreach loop on the client code continues.

Note

To see what the compiler does behind the scenes, use the ILDASM.exe tool to view the intermediate language (IL) code that is generated for an iterator method.

An iterator is invoked from client code by using a foreach statement. For example, you can create an iterator for a class that returns the elements in reverse order, or that performs an operation on each element before the iterator returns it. When you create an iterator for your class or struct, you do not have to implement the whole IEnumerator interface. When the compiler detects your iterator, it will automatically generate the Current, MoveNext and Dispose methods of the IEnumerator or IEnumerator<T> interface.

Iterators Overview

  • An iterator is a section of code that returns an ordered sequence of values of the same type.

  • An iterator can be used as the body of a method, an operator, or a get accessor.

  • The iterator code uses the yield return statement to return each element in turn. yield break ends the iteration.

  • Multiple iterators can be implemented on a class. Each iterator must have a unique name just like any class member, and can be invoked by client code in a foreach statement as follows: foreach(int x in SampleClass.Iterator2){}.

  • The return type of an iterator must be IEnumerable, IEnumerator, IEnumerable<T>, or IEnumerator<T>.

  • Iterators are the basis for the deferred execution behavior in LINQ queries.

The yield keyword is used to specify the value, or values, that are returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time that the iterator is called.

Iterators are especially useful with collection classes, providing an easy way to iterate complex data structures such as binary trees.

For more information:

Example

In this example, the DaysOfTheWeek class is a simple collection class that stores the days of the week as strings. After each iteration of a foreach loop, the next string in the collection is returned.

public class DaysOfTheWeek : System.Collections.IEnumerable
{
    string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < days.Length; i++)
        {
            yield return days[i];
        }
    }
}

class TestDaysOfTheWeek
{
    static void Main()
    {
        // Create an instance of the collection class
        DaysOfTheWeek week = new DaysOfTheWeek();

        // Iterate with foreach
        foreach (string day in week)
        {
            System.Console.Write(day + " ");
        }
    }
}
// Output: Sun Mon Tue Wed Thr Fri Sat

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

Generics (C# Programming Guide)

Concepts

C# Programming Guide

Other Resources

All About Iterators