#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;


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: