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
orIEnumerator<T>
Has a method named
MoveNext
for iterating the sequence, and a property calledCurrent
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
orIEnumerable<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:
classEnumerator
// typically implements IEnumerator // or IEnumerator<T> { publicIteratorVariableType
Current { get {...} } public bool MoveNext( ) {...} } classEnumerable
// typically implements IEnumerable // or 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 the word “beer”
without using a foreach
statement:
var enumerator = "beer".GetEnumerator();
while (enumerator.MoveNext())
{ var element = enumerator.Current;
Console.WriteLine ...
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.