
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating an Iterator on a Generic Type
|
333
foreach (int i in cntnr.ReverseOrderStep(3))
{
Console.WriteLine(i);
}
In each of the last two examples, the iterator method accepts an integer value, step,
that determines how many items will be skipped.
See Also
See the “Iterators,” “yield,” “IEnumerator Interface,” and “IEnumerable Interface”
topics in the MSDN documentation.
6.3 Creating an Iterator on a Generic Type
Problem
You want elements contained in your generic type to be enumerated using the
foreach statement.
Solution
Add an iterator to your generic type, as shown here:
public class ShoppingList<T>
{
public ShoppingList( ) {}
private List<T> _items = new List<T>( );
public void AddItem(T item)
{
_items.Add(item);
}
// Iterator
public IEnumerator<T> GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
}
The following code creates a new ShoppingList<T> 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 ShoppingList object and fill it with data.
ShoppingList<string> scart = new ShoppingList<string>( );