#563 – Enumerable Types Can Generate Multiple Enumerators

Each time that the GetEnumerator method in an enumerable type is called, an independent enumerator is generated.  Each enumerator keeps track of its own position in the parent sequence.

In the example below, nested foreach statements each iterate over the same collection.  The outer foreach statement results in one enumerator and the inner foreach statement results in the generation of a new enumerator for each pass of the outer foreach.

In this case, the ability to generate multiple independent enumerators is necessary, so that we can have overlapping foreach statements.

            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            foreach (int i in nums)
                foreach (int j in nums)
                    Console.WriteLine("{0} x {1} = {2}", i, j, i * j);

Advertisements

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: