Tested with Microsoft Visual C# 2005 Beta 1, .Net 2.0.40607.42
Iterators allow you to easily create enumerable classes: classes that allow you to iterate through their
collection of values via a foreach-in loop. Classes that implement the IEnumerable()
interface allow you to use foreach-in against them. The IEnumerable interface demands
that you implement a GetEmumerator method that returns an IEnumerator object.
It's the IEnumerator object that allows a foreach-in to work the way it does.
The new iterator pattern makes use of the yield keyword. Using yield eliminates the
need for you to have to actually create and implement an IEnumerator object. It does it
for you. yield handles all of the storage and retrieval operations that come with
GetEnumerator().
The Old Way of Creating Enumerable Classes:
public class MyOldEnumerableClass
{
private String[] m_MyStrings;
public MyOldEnumerableClass()
{
this.m_MyStrings = new String[1000000];
for (int i = 0; i <= 999999; i ++)
this.m_MyStrings[i] = "Hello!";
}
public System.Collections.IEnumerator GetEnumerator()
{
// m_MyStrings.GetEnumerator() does all of the work:
return this.m_MyStrings.GetEnumerator();
}
}
The New Way of Creating Enumerable Classes:
public class MyNewEnumerableClass
{
private String[] m_MyStrings;
public MyNewEnumerableClass()
{
this.m_MyStrings = new String[1000000];
for (int i = 0; i <= 999999; i++)
this.m_MyStrings[i] = "Hello!";
}
public System.Collections.IEnumerator GetEnumerator()
{
// yield does all of the work:
foreach (String str in this.m_MyStrings)
yield return str;
}
}