
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
338
|
Chapter 6: Iterators and Partial Types
Discussion
Adding a default iterator to a type via the GetEnumerator method is easy and straight-
forward. However, this forces you to give up some flexibility. For example, using the
GetEnumerator method prevents you from passing in any parameters. If you can pass
in parameters, you can more easily control the way the
foreach loop iterates over the
items in this type.
The
GetRange iterator accepts both a starting and ending index value. These values
indicate the index value at which to start iterating (
start) and the index value at
which the iterations will cease (
end). The following code shows how this iterator is
used:
public static void TestIteratorMethod( )
{
//Create Foo object and fill it with data.
Foo f = new Foo( );
f.AddItem("item1");
f.AddItem("item2");
f.AddItem("item3");
f.AddItem("item4");
f.AddItem("item5");
f.AddItem("item6");
// Display all data in Foo object.
foreach (string s in f.GetRange(3, 4))
{
Console.WriteLine(s);
}
}
}
if (end < start)
{
throw (new IndexOutOfRangeException(
"the end index cannot be less than the start parameter."));
}
if (end >= _items.Count)
{
throw (new IndexOutOfRangeException(
"the end index cannot be greater than or equal to the length of the list."));
}
for (int index = start; (index < _items.Count) ...