O'Reilly logo

C# 3.0 Pocket Reference, 2nd Edition by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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; Console.WriteLine ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required