Enumeration and Iterators

Enumeration

An enumerator is a read-only, forward-only cursor over a sequence of values; it is an object that implements System.Collections.IEnumerator or System.Collections.Generic.IEnumerator<T>.

The foreach statement iterates over an enumerable object. An enumerable object is the logical representation of a sequence. It is not itself a cursor, but an object that produces cursors over itself. An enumerable either implements IEnumerable/IEnumerable<T> or has a method named GetEnumerator that returns an enumerator.

The enumeration pattern is as follows:

class Enumerator   // Typically implements IEnumerator<T>
{
  public IteratorVariableType Current { get {...} }
  public bool MoveNext() {...}
}
class Enumerable   // Typically implements IEnumerable<T>
{
  public Enumerator GetEnumerator() {...}
}

Here is the high-level way to iterate through the characters in the word beer using a foreach statement:

foreach (char c in "beer") Console.WriteLine (c);

Here is the low-level way to iterate through the characters in beer without using a foreach statement:

using (var enumerator = "beer".GetEnumerator())
  while (enumerator.MoveNext())
  {
    var element = enumerator.Current;
    Console.WriteLine (element);
  }

If the enumerator implements IDisposable, the foreach statement also acts as a using statement, implicitly disposing the enumerator object.

Collection Initializers

You can instantiate and populate an enumerable object in a single step. For example:

using System.Collections.Generic; ... ...

Get C# 5.0 Pocket Reference 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.