CHAPTER 8 WORKING WITH INTERFACES
}
foreach (Car c in carArray)
{
yield return c;
}
}
Notice that the new method allows the caller to obtain the subitems in sequential order, as well as in
reverse order, if the incoming parameter has the value true. You could now interact with our new
method as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with the Yield Keyword *****\n");
Garage carLot = new Garage();
// Get items using GetEnumerator().
foreach (Car c in carLot)
{
Console.WriteLine("{0} is going {1} MPH",
c.PetName, c.CurrentSpeed);
}
Console.WriteLine();
}
// Get items (in reverse!) using named iterator.
foreach (Car c in carLot.GetTheCars(true))
{
Console.WriteLine("{0} is going {1} MPH",
c.PetName, c.CurrentSpeed);
}
Console.ReadLine();
As you might agree, named iterators are helpful constructs, in that a single custom container can
define multiple ways to request the returned set.
So, to wrap up our look at building enumerable objects, remember that for your custom types to
work with the C# foreach keyword, the container must define a method named GetEnumerator(), which
has been formalized by the IEnumerable interface type. The implementation of this method is typically
achieved by simply delegating it to the internal member that is holding onto the subobjects; however, it
is also possible to make use of the yield return syntax to provide multiple “named iterator” methods.
Source Code The CustomEnumeratorWithYield project is located under the Chapter 8 subdirectory.
307