#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);
        }
Advertisement

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

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

  1. Pingback: #560 – Returning an Enumerator from an Iterator « 2,000 Things You Should Know About C#

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 )

Connecting to %s

%d bloggers like this: