
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
336
|
Chapter 6: Iterators and Partial Types
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
}
The following code creates a new NGShoppingList object and fills it with strings; it
then proceeds to use a
foreach loop to enumerate and display each string:
public static void TestShoppingCart( )
{
// Create NGShoppingList object and fill it with data.
NGShoppingList scart = new NGShoppingList( );
scart.AddItem("item1");
scart.AddItem("item2");
scart.AddItem("item3");
scart.AddItem("item4");
scart.AddItem("item5");
scart.AddItem("item6");
// Display all data in NGShoppingCart object.
foreach(string s in scart)
{
Console.WriteLine(s);
}
}
Discussion
Adding an iterator to a type is fairly straightforward. You simply add a GetEnumerator
method that accepts no arguments and returns an IEnumerator<string> type. In addi-
tion to this, the enumerator must have
public accessibility. This GetEnumerator
method is called by the foreach loop to determine what object is returned by this
loop on every iteration.
The code that you write inside of the
GetEnumerator method is what actually does the
work of determining the next object to be returned by the
foreach loop. This is
accomplished through the use of the
yield return statement. For example, in this
recipe you simply ...