#558 – Using an Iterator Within a for Loop

An iterator block could contain a series of yield statements to return individual elements of a sequence.

        private static IEnumerable<Dog> ListOfDogs()
            yield return new Dog("Jack", 17);
            yield return new Dog("Kirby", 14);
            yield return new Dog("Lassie", 72);

More commonly, however, an iterator block will contain a loop that generates a sequence, with a yield statement that returns a new element of the sequence each time through the loop.

The example below returns a portion of the Fibonacci sequence, with each element in the sequence after the first two returned by a yield statement within the loop.

        static void Main()
            foreach (int i in Fibonacci(20))

        private static IEnumerable<int> Fibonacci(int numInSeq)
            yield return 0;
            yield return 1;

            int last = 0;
            int current = 1;

            for (int i = 0; i < (numInSeq - 2); i++)
                int next = last + current;
                yield return next;
                last = current;
                current = next;