SIGN UP MEMBER LOGIN:    
ARTICLE

C# Iterations: IEnumerator, IEnumerable and Yield

Posted by Ilker Kucuk Articles | C# Language February 16, 2010
In this article you will learn how to use C# Iterations: IEnumerator, IEnumerable and Yield
Reader Level:

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 incriments 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. 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. IEnumerator inherits IDisposible for performance only.

Using The Yield Keyword

yield keyword is introduced by C# 2.0 in order to implement iteartion easier. On the other hand it has some disadventages. Let's first look at the yield keyword.

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.

Criticism of the keyword "yield"

"yield" has a couple of drawbacks first of all it is designed to simplify implementing iterations. But 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.

Second problem is that "yield" does not make sense in Object Oriented paradigm just like delegates. I believe as long as languages stick to a single paradigm they become more understandable and structured. When Microsoft introduced C# they decided to use delegates as an event mechanism, instead of interfaces. Delegates are function pointers and have no meaning in OOP. A similar problem exists for yield too, when you look at the above example, the method signature tells you that GetPowersofTwo will return an object implemented IEnumerable. But it is not the case.

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor