New Features in C# 2.0—Generic Iterators: How do I do that?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

How do I do that?

To simplify the process of creating iterators, we’ll begin by simplifying both the Pilgrim class and the Linked List class. The Linked List class will forgo all use of nodes and will store its contents in a fixed-size array (as the simplest type-safe container imaginable). Thus, it is a Linked List in name only! This will allow us to focus on the implementation of the IEnumerator interface, as shown in Example 1-4.

Example 1-4. Implementing IEnumerator, simplified

#region Using directives
 
using System;
using System.Collections.Generic;
using System.Text;
 
#endregion
 
namespace SimplifiedEnumerator
{
  // simplified Pilgrim
  public class Pilgrim
  {
    private string name;
    public Pilgrim(string name)
    {
      this.name = name;
    }
    public override string ToString( )
    {
      return this.name;
    }
  }
 
  // simplified Linked List
  class NotReallyALinkedList<T> : IEnumerable<T>
  {
    // the entire linked list is stored in this
    // fixed size array
    T[ ] myArray;
    
    // constructor takes an array and stores the members
    public NotReallyALinkedList(T[ ] members)
    {
      myArray = members;
    }
  
    // implement the method for IEnumerable
    IEnumerator<T> IEnumerable<T>.GetEnumerator( )
    {
      foreach (T t in this.myArray)
      {
        yield return t;
      }
    }
  
    System.Collections.IEnumerator
      System.Collections.IEnumerable.GetEnumerator()
    {
      throw new NotImplementedException();
    }
  }
 
  class Program
  {
    static void Main(string[ ] args)
    {
      // hardcode a string array of Pilgrim objects
      Pilgrim[ ] pilgrims = new Pilgrim[5];
      pilgrims[0] = new Pilgrim("The Knight");
      pilgrims[1] = new Pilgrim("The Miller");
      pilgrims[2] = new Pilgrim("The Reeve");
      pilgrims[3] = new Pilgrim("The Cook");
      pilgrims[4] = new Pilgrim("The Man Of Law");
 
      // create the linked list, pass in the array
      NotReallyALinkedList<Pilgrim> pilgrimCollection =
        new NotReallyALinkedList<Pilgrim>(pilgrims);
  
      // iterate through the linked list
      foreach (Pilgrim p in pilgrimCollection)
      {
        Console.WriteLine(p);
      }
    }
  }
}

Output:

The Knight
The Miller
The Reeve
The Cook
The Man Of Law


Previous_Page_.gif Next_Page_.gif

Personal tools