Listing 6.4
shows the complete implementation of the GetEnumerator method in C# 2.
public IEnumerator GetEnumerator()
{
for (int index=0; index < values.Length; index++)
{
yield return values[(index+startingPoint)%values.Length];
}
}
Listing 6.4 Iterating through the sample collection with C# 2 and yield return
Much
simpler, isn??™t
it?
166 CHAPTER 6 Implementing iterators the easy way
Four lines of implementation, two of which are just braces. Just to make it clear, that
replaces the whole of the IterationSampleIterator class. Completely. At least in the
source code??¦ Later on we??™ll see what the compiler has done behind our back, and
some of the quirks of the implementation it??™s provided, but for the moment let??™s look
at the source code we??™ve used.
The method looks like a perfectly normal one until you see the use of yield
return. That??™s what tells the C# compiler that this isn??™t a normal method but one
implemented with an iterator block. The method is declared to return an IEnumerator,
and you can only use iterator blocks to implement methods1 that have a return type of
IEnumerable, IEnumerator, or one of the generic equivalents. The yield type of the iterator
block is object if the declared return type of the method is a nongeneric interface,
or the type argument of the generic interface otherwise. For instance, a method
declared to return IEnumerable
would have a yield type of string.
Pages:
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335