
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating Iterators That Accept Parameters
|
337
If you choose to implement the IEnumerator interface on the NGShoppingList class,
the class declaration will change to look like this:
public class NGShoppingList : IEnumerable
Regardless of the method you choose, the operation of the iterator and the foreach
loop is identical.
See Also
See the “Iterators,” “IEnumerator Interface,” and “IEnumerable Interface” topics in
the MSDN documentation.
6.5 Creating Iterators That Accept Parameters
Problem
You need to add a new iterator that accepts parameters to a type in order for the iter-
ator to do special processing during the looping operation.
Solution
Add a method that is public, returns an IEnumerable, and uses the yield return state-
ment, as shown in Example 6-3.
Example 6-3. Creating iterators that accept parameters
public class Foo
{
private List<string> _items = new List<string>( );
public void AddItem(string item)
{
_items.Add(item);
}
public IEnumerator GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
// An iterator that accepts a starting index and an ending index to iterate over
public IEnumerable GetRange(int start, int end)
{
if (start < 0)
{
throw (new IndexOutOfRangeException
("the start index cannot be less than zero.")); ...