Information Technology Reference
In-Depth Information
Iterators
Enumerable classes and enumerators are used extensively in the .NET collection classes, so it's
important that you know how they work. But now that you know how to create you own enu-
merable classes and enumerators, you might be pleased to learn that, with C# 2.0, the language
now has a much simpler way of creating enumerators. In fact, the compiler will create them for
you. The construct producing this is called an iterator .
Before I explain the details, let's take a look at two examples. The following method decla-
ration implements an iterator.
The iterator returns a generic enumerator that returns three items of type string .
￿
￿The yield return statements declare that this is the next item in the enumeration .
Return a generic enumerator.
IEnumerator<string> BlackAndWhite() // Version 1
{
yield return "black"; // yield return
yield return "gray"; // yield return
yield return "white"; // yield return
}
The following method declaration is another version that produces the same end result:
Return a generic enumerator.
IEnumerator<string> BlackAndWhite() // Version 2
{
string[] TheColors = { "black", "gray", "white" };
for (int i = 0; i < TheColors.Length; i++)
yield return TheColors[i]; // yield return
}
I haven't explained the yield return statement yet, but on inspecting these code seg-
ments, you might have the feeling that something is different about this code. It doesn't seem
quite right. What exactly does the yield return statement do?
For example, in the first version, if the method returns on the first yield return statement,
then the last two statements can never be reached. If it doesn't return on the first statement, but
continues through to the end of the method, then what happens to the values? And in the second
version, if the yield return statement in the body of the loop returns on the first iteration, then
the loop will never get to any subsequent iterations.
And besides all that, an enumerator doesn't just return all the elements in one shot—it
returns a new value with each access of the Current property. So how does this give you an enu-
merator? Clearly this code is different than anything shown before.
Search WWH ::




Custom Search