C# Iterations: IEnumerator, IEnumerable and Yield

Directly using IEnumerator for iterations

Enumerators are used to read data in the collection. The foreach statement hides the complexity of the enumerators, but you can directly manipulate IEnumerator for customized iterations. Let's do an example:

Code

List<string> myList = new List<string>();
for (int i = 0; i < 10; i++)
{
    myList.Add("Item " + i.ToString());
}

IEnumerator<string> myEnum = myList.GetEnumerator();
 
myEnum.Reset();           
myEnum.MoveNext();
myEnum.MoveNext();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);
myEnum.MoveNext();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);

myEnum.Reset();

myEnum.MoveNext();

System.Console.WriteLine(myEnum.Current);

Output:

Item 2
Item 4
Item 0

In order to reach the first element, you should run MoveNext method of Enumerator. Initial Position of Enumerator does not point the first element.

Implementing IEnumerable and IEnumerator on your custom objects

IEnumerable interface should be implemented in order to use your custom objects in the form of a collection (series of values or objects). Which means you can use it directly with the foreach statement. IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator. Let's do an example: PowersOfTwo class implements IEnumerable so any instance of this class can be accessed as a collection.

class PowersOfTwo : IEnumerable<int>
{      
    public IEnumerator<int> GetEnumerator()
    {
        return new PowersOfTwoEnumerator();
    }       
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }       
}

Test

PowersOfTwo p2 = new PowersOfTwo();
foreach (int p in p2)
{
    System.Console.WriteLine(p);
}

Output

2 4 8 16 32 64 128 256 512 1024

Actually the magic trick lies in the PowersOfTwoEnumerator Class

class PowersOfTwoEnumerator : IEnumerator<int>
{
    private int index = 0;

    public int Current
    {
        get { return (int)System.Math.Pow(2, index); }
    }

    object System.Collections.IEnumerator.Current
    {
        get { return Current; }
    }

    public bool MoveNext()
    {
        index++;

        if (index > 10)
            return false;
        else
            return true;
    }

    public void Reset()
    {
        index = 0;
    }

    public void Dispose()
    {
    }
}

Current returns the same element until MoveNext is called. Initial index is zero each MoveNext method increments the index by 1 up to 10 then it returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. 

As general rules:

If the last call to MoveNext returned false, Current is undefined. You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.

Using The Yield Keyword

yield keyword is introduced by C# 2.0 in order to simplify implementation iterator pattern in your custom objects. 

public IEnumerable<int> GetPowersofTwo()
{
   for (int i = 1; i < 10; i++)
       yield return (int)System.Math.Pow(2, i);
   yield break;
}

Yield is not a feature of the .Net runtime. It is just a C# language feature. During compilation Compiler converts yield method and its class to instances of IEnumerable and IEnumerator implemented classes.

I strongly suggest programmers to be careful when using yield, it can be used to write very ill designed code (like goto). There are many bad examples therefore I am not going to write one here. But using it for other than the intended purpose will make your code hard to follow.


Similar Articles