Patterns and Iterators in C# - Enumeration and Iterators
(Page 2 of 4 )
Enumeration
An enumerator is a read-only, forward-only cursor over a sequence of values. An enumerator is an object that either:
- ImplementsIEnumeratororIEnumerator<T>
- Has a method namedMoveNext for iterating the sequence, and a property calledCurrentfor getting the current element in the sequence
Theforeachstatement 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 object either:
- ImplementsIEnumerableorIEnumerable<T>
- Has a method namedGetEnumeratorthat returns an enumerator
IEnumeratorandIEnumerableare defined inSystem.Collections.
IEnumerator<T>andIEnumerable<T>are defined inSystem.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 aforeachstatement:
foreach (char c in "beer")
Console.WriteLine (c);
Here is the low-level way of iterating through the characters in “beer” without using aforeachstatement:
var enumerator = "beer".GetEnumerator();
while (enumerator.MoveNext())
{
var element = enumerator.Current;
Console.WriteLine (element);
}
Theforeachstatement also acts as ausing statement, implicitly disposing the enumerator object.
Chapter 7 explains the enumeration interfaces in further detail.
Next: Iterators >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|