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:
classEnumerator// Typically implements IEnumerator<T> { publicIteratorVariableTypeCurrent { get {...} } public bool MoveNext() {...} } classEnumerable// Typically implements IEnumerable<T> { publicEnumeratorGetEnumerator() {...} }
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; ... ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access