#1,195 – Iterator Produces Only as Many Elements as Are Needed

When implementing an iterator, you write code that generates a sequence of elements using the yield return statement to return each consecutive element.

The full body of the iterator code may not execute.  Only the code required to return the elements iterated upon is executed.  In the example below, we iterate over a sequence produced by an iterator, using foreach.

Executing this code, only a portion of the AllMyDogs() method is executed, since we exit early out of  the foreach loop.

            static void Main(string[] args)
                foreach (Dog d in AllMyDogs())
                    if (d.Breed == Breed.JackRussell)


            private static IEnumerable<Dog> AllMyDogs()
                Console.WriteLine("* returning Kirby");
                yield return new Dog("Kirby", Breed.BorderCollie, 14);
                Console.WriteLine("* returning Jack");
                yield return new Dog("Jack", Breed.JackRussell, 15);
                Console.WriteLine("* returning Ruby");
                yield return new Dog("Ruby", Breed.Mutt, 4);
                Console.WriteLine("* returning Lassie");
                yield return new Dog("Lassie", Breed.Collie, 12);
                Console.WriteLine("* returning Foofoo");
                yield return new Dog("Foofoo", Breed.Sheltie, 8);


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: