Type Summary

						public interface IEnumerable
{
  // Methods
     IEnumerator GetEnumerator ();
}

BA It is interesting to look at how the C# foreach support works with types that implement IEnumerable.

For a C# program that looks like this:

foreach (int v in collection) { ... }

The C# compiler generates code that looks something like this:

 1: IEnumerable ie = (IEnumerable) collection;
 2: IEnumerator e = ie.GetEnumerator();
 3: try {
 4:   while (e.MoveNext()) {
 5:      int v = (int) e.Current;
 6:      ...
 7:   }
 8: }
 9: finally {
10:   if (e is IDisposable) {
11:      ((IDisposable)e).Dispose();
12:   }
13: }

In line 1, you see the first thing we do is cast the collection to the IEnumerable interface. Then in line 2 we get the IEnumerator and in line 4 we start iterating ...

Get .NET Framework Standard Library Annotated Reference, Volume 1: Base Class Library and Extended Numerics Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.