
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Adding Multiple Iterators on a Single Type
|
339
This code displays the following:
item4
item5
which are the string elements at the third and fourth index in the _items list in the
object.
Two out-of-bounds situations can occur. The first is when the
end parameter is set to
a value that is past the end of the
_items list. The following code shows this:
foreach (string s in f.GetRange(0, 50))
{
Console.WriteLine(s);
}
This foreach loop will display all items in the _items list. This is because you have set
up the
for loop in the GetRange iterator method to handle this situation. The for
loop’s conditional expression is shown here:
for (int index = start; (index < _items.Count) && (index <= end); index++)
The for loop will stop looping either when the index loop counter is greater than the
end parameter or when it goes past the end of the _items list. Another out-of-bounds
situation is when the
start parameter is less than the initial index in the _items list,
which is zero. The following code starts iterating at a negative
start index:
foreach (string s in f.GetRange(-3, 5))
{
Console.WriteLine(s);
}
This causes an IndexOutOfRangeException to be thrown.
See Also
See the “Iterators,” “IEnumerator Interface,” and “IEnumerable Interface” topics in
the MSDN documentation.
6.6 Adding Multiple Iterators on ...