Information Technology Reference
In-Depth Information
// Skip the foreach and manually use the enumerable and enumerator.
IEnumerable<string> ieable = cc.Reverse();
IEnumerator<string> ieator = ieable.GetEnumerator();
while (ieator.MoveNext())
Console.Write("{0} ", ieator.Current);
Console.WriteLine("");
}
}
}
Using an Iterator to Produce an Enumerator
In the previous example, iterators were used to produce an enumerable class. In this example,
iterators are used to produce an enumerator class. Additionally, it shows the iterators imple-
mented as properties that return the enumerators, rather than methods.
The code declares two properties that define two different enumerators. The
GetEnumerator method returns one of the two enumerators, depending on the value of the
Boolean variable ColorFlag . If ColorFlag is true , the Colors enumerator is returned. Otherwise,
the BlackAndWhite enumerator is returned.
class MyClass: IEnumerable<string>
{
bool ColorFlag = true;
public MyClass(bool flag) // Constructor
{ ColorFlag = flag; }
IEnumerator<string> BlackAndWhite // Property--enumerator iterator
{
get {
yield return "black";
yield return "gray";
yield return "white";
}
}
Search WWH ::




Custom Search