Iterators in c#


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.


Code Example: Iterators
using System;
using System.Collections;

namespace Client.Chapter_3___Structs__Enums__Arrays_and_Collections
{
      public class List
      {
            internal object[] elements;
            internal int count;
            public IEnumerable Elements()
            {
                  foreach (object o in elements)
                  {
                        yield o;
                  }
            }
      }
    public class ListUser
    {
          static void Main(string[] args)
          {
                 List list = new List();
                 foreach (object obj in list.Elements())
                 {
                       //Do something with obj
                 }
          }
    }




Added on January 5, 2008 Comment
}