New Features in C# 2.0—GetEnumerator: What just happened?

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.

What just happened?

The linked list implements its enumerator to call foreach on the head node (which you can do because Node also implements IEnumerable). Then you yield the data object you get back from the node:

IEnumerator<T> IEnumerable<T>.GetEnumerator( )
{
  foreach (Node<T> node in this.headNode)
  {
    yield return node.Data;
  }
}

This gives Node the responsibility of iterating through the node list, which is accomplished, once again, using the yield statement in its own GetEnumerator method.

IEnumerator<Node<T>> IEnumerable<Node<T>>.GetEnumerator( )
{
  Node<T> nextNode = this;
  do
  {
    Node<T> returnNode = nextNode;
    nextNode = nextNode.next;
    yield return returnNode;
  } while (nextNode != null);
}

You initialize nextNode to the current node, and then you begin your do…while loop. This is guaranteed to run at least once. returnNode is set to nextNode, and then, once that is stashed away, nextNode is set to its next node (that is, the next node in the list). Then you yield returnNode. Each time through you are returning the next node in the list until nextNode is null, at which time you stop.


When you use the yield statement, the C# compiler automatically generates a nested implementation of IEnumerator for you. It keeps its own state; you simply tell it which value to yield.


Previous_Page_.gif Next_Page_.gif

Personal tools