Information Technology Reference
In-Depth Information
Enumerators and Enumerable Types
In Chapter 14, you saw that you can use a foreach statement to cycle through the elements of
an array. In this chapter, you'll take a closer look at arrays and see why they can be processed
by foreach statements. You'll also look at how you can add this capability to you own user-
defined classes. Later, I'll discuss the use of iterators.
Using the foreach Statement
When you use the foreach statement with an array, the statement presents you with each
element in the array, one by one, allowing you to read its value.
For example, the following code declares an array with four elements, and then uses a
foreach loop to print out the values of the items.
int[] Arr1 = { 10, 11, 12, 13 }; // Define the array.
foreach (int item in Arr1) // Enumerate the elements.
Console.WriteLine("Item value: {0}", item);
This code produces the following output:
Item value: 10
Item value: 11
Item value: 12
Item value: 13
Why does this work, apparently magically, with arrays? The reason is that an array can pro-
duce, upon request, an object called an enumerator . The enumerator can return the elements
of the array, one by one, in order, as they are requested. The enumerator “knows” the order of
the items, and keeps track of where it is in the sequence. It then returns the current item when
it is requested.
For types that have enumerators, there must be a way of retrieving them. The standard
way of retrieving an object's enumerator in .NET is to call the object's GetEnumerator method.
Types that implement a GetEnumerator method are called enumerable types , or just enumera-
bles . Arrays are enumerables.
Figure 20-1 illustrates the relationship between enumerables and enumerators.
Search WWH ::




Custom Search