Free mag vol1 | Page 365

CHAPTER 8  WORKING WITH INTERFACES  Note You might want to rename the namespace containing the Car and Radio types to CustomEnumerator, to avoid having to import the CustomException namespace within this new project. Now, insert a new class named Garage that stores a set of Car objects within a System.Array: // Garage contains a set of Car objects. public class Garage { private Car[] carArray = new Car[4]; } // Fill with some Car objects upon startup. public Garage() { carArray[0] = new Car("Rusty", 30); carArray[1] = new Car("Clunker", 55); carArray[2] = new Car("Zippy", 30); carArray[3] = new Car("Fred", 30); } Ideally, it would be convenient to iterate over the Garage object’s subitems using the foreach construct, just like an array of data values: // This seems reasonable ... public class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with IEnumerable / IEnumerator *****\n"); Garage carLot = new Garage(); } } // Hand over each car in the collection? foreach (Car c in carLot) { Console.WriteLine("{0} is going {1} MPH", c.PetName, c.CurrentSpeed); } Console.ReadLine(); Sadly, the compiler informs you that the Garage class does not implement a method named GetEnumerator(). This method is formalized by the IEnumerable interface, which is found lurking within the System.Collections namespace. 303