New Features in C# 2.0—Generic Iterators: 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?

In this example, the linked list is greatly simplified to keep its members in an array (in fact, it is not really a linked list at all). Because you’ve made your pseudo-LinkedList enumerable, however, now you can enumerate the Pilgrims in the pilgrims collection using a foreach loop.

When you write:

foreach (Pilgrim p in pilgrimCollection)

the C# compiler invokes the GetEnumerator method of the class. Internally, it looks more or less like this:

Enumerator e = 
  pilgrimCollection.GetEnumerator( );
while (e.MoveNext( ))
{
  Pilgrim p = e.Current;
}

As noted earlier, in C# 2.0 you do not have to worry about implementing MoveNext( ) or the current property. You need only use the new C# keyword yield.


TIP
You use yield only in iterator blocks. It either provides a value to the enumerator object or it signals the end of the iteration:
yield return expression;
yield break;


If you step into the foreach loop with the debugger, you’ll find that each time through the foreach loop, the GetEnumerator method of the linked list is called, and each time through the next member in the array, it is yielded back to the calling foreach loop.


Whenever you call foreach, the compiler internally translates it to a call to GetEnumerator.


Previous_Page_.gif Next_Page_.gif

Personal tools