#557 – Using an Iterator to Return the Elements of an Enumerable Type

An iterator is a block of code that produces an enumerator.  (An enumerator is an object that knows how to move through a sequence of elements, typically implemented in an enumerable type that represents a collection of elements).

You can think of the iterator as the code that generates an enumerator, whereas a foreach loop is the code that makes use of the enumerator.

An iterator block is a block of code that includes one or more yield statements, each of which returns the next item in the sequence.  The iterator block can return either an enumerable type or an enumerator.  In the example below, the enumerable type IEnumerable<Dog> is returned.

        static void Main()
        {
            foreach (Dog d in ListOfDogs())
                Console.WriteLine(d.Name);
        }

        private static IEnumerable<Dog> ListOfDogs()
        {
            yield return new Dog("Jack", 17);
            yield return new Dog("Kirby", 14);
            yield return new Dog("Lassie", 72);
            yield return new Dog("Rin Tin Tin", 94);
        }
Advertisements