BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 2.0+

C# Iterators

C# 2.0 introduced iterators. Iterators can be added to a class to allow traversing of a sequence of values with the foreach command. Although possible in earlier language versions, iterators remove the need to manually implement the IEnumerable interface.

Executing the Iterator

Now that the iterators are defined, we can traverse the class's values with a simple foreach loop. In the following sample, a new object is created and used as the target for a loop. Try executing the sample to see the results. It is also worthwhile stepping through the code using the Visual Studio debugger in order to see the operation of the iterator.

MyEnumerableClass mec = new MyEnumerableClass();

foreach (string fruit in mec)
    Console.WriteLine(fruit);

/* OUTPUT

Apple
Banana
Clementine
Damson
Elderberry
Fig
Grape
Huckleberry
Indian Prune
Jujube
Kiwi
Lime

*/

Creating an Enumerable Method

If you wish to create more than one iterator for a single class, or you would prefer to access the iterator using a method or a property, that member must return an IEnumerable or IEnumerable<T> object. The internal implementation of the method can be identical to that of the previous example.

To demonstrate, we can add a method that implements an iterator that returns the fruit names in reverse order:

public IEnumerable<string> Reverse()
{
    for (int i = _fruitList.Length - 1; i >= 0; i--)
    {
        yield return _fruitList[i];
    }
}

To loop through the sequence, the method is called within the foreach loop:

foreach (string fruit in mec.Reverse())
{
    Console.WriteLine(fruit);
}

Using Yield Break

When using yield return statements, the iterator continues to execute until all of the yield statements have been processed and the method ends normally. This signifies the termination of the iterator and causes any foreach loop to end. However, sometimes you will want to stop the enumerator earlier, perhaps in response to a condition being met. When this occurs, you can use the yield break statement.

To demonstrate, add the following method to the MyEnumerableClass class. This method accepts a parameter, which may contain the name of a fruit. If the name is found whilst looping through the array, it is retuned. However, on the next iteration the yield break statement is encountered so the loop ends early.

public IEnumerable<string> Limited(string lastItem)
{
    for (int i = 0; i < _fruitList.Length; i++)
    {
        yield return _fruitList[i];

        if (_fruitList[i] == lastItem)
        {
            yield break;
        }
    }
}

Try executing a foreach loop for this method, passing a fruit name to see the loop exiting before all of the fruits are returned.

4 December 2008