CHAPTER 8 WORKING WITH INTERFACES
}
public IEnumerator GetEnumerator()
{
foreach (Car c in carArray)
{
yield return c;
}
}
Notice that this implementation of GetEnumerator() iterates over the subitems using internal
foreach logic and returns each Car to the caller using the yield return syntax. The yield keyword is used
to specify the value (or values) to be returned to the caller’s foreach construct. When the yield return
statement is reached, the current location in the container is stored, and execution is restarted from this
location the next time the iterator is called.
Iterator methods are not required to make use of the foreach keyword to return its contents. It is
also permissible to define this iterator method as follows:
public IEnumerator GetEnumerator()
{
yield return carArray[0];
yield return carArray[1];
yield return carArray[2];
yield return carArray[3];
}
In this implementation, notice that the GetEnumerator() method is explicitly returning a new value
to the caller with each pass through. Doing so for this example makes little sense, given that if we were to
add more objects to the carArray member variable, our GetEnumerator() method would now be out of
sync. Nevertheless, this syntax can be useful when you want to return local data from a method for
processing by the foreach syntax.
Building a Named Iterator
It is also interesting to note that the yield keyword can technically be used within any method,
regardless of its nam e. These methods (which are technically called named iterators) are also unique in
that they can take any number of arguments. When building a named iterator, be very aware that the
method will return the IEnumerable interface, rather than the expected IEnumerator-compatible type. To
illustrate, you could add the following method to the Garage type:
public IEnumerable GetTheCars(bool ReturnRevesed)
{
// Return the items in reverse.
if (ReturnRevesed)
{
for (int i = carArray.Length; i != 0; i--)
{
yield return carArray[i-1];
}
}
else
{
// Return the items as placed in the array.
306