Iterators (C# Programming Guide) 

Iterators are a new feature in C# 2.0. An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface. Instead, you provide just an iterator, which simply traverses the data structures in your class. When the compiler detects your iterator, it will automatically generate the Current, MoveNext and Dispose methods of the IEnumerable or IEnumerable 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. For more information, see yield.

  • 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, or IEnumerator.

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

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

For more information:

Example

In this example, the class DaysOfTheWeek 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[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < m_Days.Length; i++)
        {
            yield return m_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 following sections in the C# Language Specification:

  • 22 Iterators

See Also

Concepts

C# Programming Guide
Generics (C# Programming Guide)