Iterators in c#

Posted On
January 5, 2008 by Krishna
Language:

In the past, to enumerate through an object that held a collection, your objects needed to inherit and implement IEnumerable. In addition, they needed to support an internal means of storing the state of the object being enumerated. This approach works in versions 1.0 and 1.1 of C#, but new functionality has been added to greatly simplify this process. Today, we have the foreach statement. You no longer need to do all the work to get your objects to enumerate with the foreach-style iterators.

Iterators handle the messy chore of implementing the enumerator pattern on your behalf. Rather than needing to create the classes and build the state machine, the C# compiler will place the code you have written in your iterators into the appropriate classes. The following example illustrates how iterators work.