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;
}
}
Excellent Read. There are not that many articles on C# Iterators.
I did a search on www.aaabooksearch.com for books on C# and found a bunch. Hopefully that will add to my knowledge too.By Cesadolvi @ 4/5/2007 3:08:27 AM
Thanks for explaining it in a concise, straightforward way. All the other tutorials I've checked out on iterators are extremely wordy and only show pieces of the code. Nice work!By brgllxgg @ 6/6/2007 8:03:01 PM