Iterator Pattern - TechNet Articles - United States (English) - TechNet Wiki

This pattern provides a way to access elements from an aggregate sequentially. Microsoft's IEnumerable is one of the example of this pattern. Let me introduce this pattern using this interface.



public class Element
  /div>

Iterator Pattern

This pattern provides a way to access elements from an aggregate sequentially. Microsoft's IEnumerable is one of the example of this pattern. Let me introduce this pattern using this interface.

{
        public string Name { get; set; }
    }
 
    public class Iterator: IEnumerable<element>
    {
        public Element[] array;
        public Element this[int i]
        {
            get
            {
                return array[i];
            }
        }
 
        #region IEnumerable<element> Members
 
        public IEnumerator<element> GetEnumerator()
        {
            foreach (Element arr in this.array)
                yield return arr;
        }
 
        #endregion
 
        #region IEnumerable Members
 
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            foreach (Element arr in this.array)
                yield return arr;
        {
            }
 
        #endregion
    }

The iterator pattern in .NET can be implemented using IEnumerator and IEnumerable. An IEnumerator is an iterator object which has methods called MoveNext and Current. When the MoveNext is called for an IEnumerator the underlying sequence is moved one element further and the Current property is set to the current object until it reaches the last element when the movenext fails with a false return value. The IEnumerable implemented for all collection or sequence in .NET creates an object of IEnumerator for that particular sequence and gets the object to us. 

The special keyword yield in C# automatically creates the IEnumerable and IEnumerator without need for the developer to implement these manually.