Enumeration and Iterators
Enumeration
An enumerator is a read-only, forward-only cursor over a sequence
of values. An enumerator 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> { publicIteratorVariableType
Current { get {...} } public bool MoveNext() {...} } classEnumerable
// Typically implements IEnumerable<T> { publicEnumerator
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
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 as in the earlier example.
Collection Initializers
You can instantiate and populate an enumerable object in a single step. For example: ...
Get C# 4.0 Pocket Reference, 3rd 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.