Enumeration and Iterators

Enumeration

An enumerator is a read-only, forward-only cursor over a sequence of values. An enumerator is an object that either:

  • Implements IEnumerator or IEnumerator<T>

  • Has a method named MoveNext for iterating the sequence, and a property called Current for getting the current element in the sequence

The foreach statement iterates over an enumerable object. An enumerable object is the logical representation of a sequence, and is not itself a cursor, but an object that produces cursors over itself. An enumerable object either:

  • Implements IEnumerable or IEnumerable<T>

  • Has a method named GetEnumerator that returns an enumerator

Note

IEnumerator and IEnumerable are defined in System. Collections. IEnumerator<T> and IEnumerable<T> are defined in System.Collections.Generic.

The enumeration pattern is as follows:

	class Enumerator   // typically implements IEnumerator
	                   // or IEnumerator<T>
	{
	  public IteratorVariableType Current { get {...} }
	  public bool MoveNext( )             {...}
	}

	class Enumerable   // typically implements IEnumerable
	                   // or IEnumerable<T>
	{
	  public Enumerator GetEnumerator( ) {...}
	}

Here is the high-level way of iterating 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 of iterating through the characters in the word “beer” without using a foreach statement:

	var enumerator = "beer".GetEnumerator();

	while (enumerator.MoveNext())
	{
	  var element = enumerator.Current; ...

Get C# 3.0 Pocket Reference, 2nd Edition 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.