1, which now has the expected output.
It??™s worth bearing in mind that this is a relatively simple example??”there??™s not a lot
of state to keep track of, and no attempt to check whether the collection has changed
between iterations. With this large burden involved to implement a simple iterator, we
shouldn??™t be surprised at the rarity of implementing the pattern in C# 1. Developers
have generally been happy to use foreach on the collections provided by the framework,
but they use more direct (and collection-specific) access when it comes to their
own collections.
So, 40 lines of code to implement the iterator in C# 1, not including comments.
Let??™s see if C# 2 can do any better.
6.2 C# 2: simple iterators with yield statements
I??™ve always been the kind of person who likes to stay up until midnight on Christmas
Eve in order to open a present as soon as Christmas Day arrives. In the same way, I
think I??™d find it almost impossible to wait any significant amount of time before showing
you how neat the solution is in C# 2.
6.2.1 Introducing iterator blocks and yield return
This chapter wouldn??™t exist if C# 2 didn??™t have a powerful feature that cut down the
amount of code you had to write to implement iterators. In some other topics the
amount of code has only been reduced slightly, or has just made something more elegant.
In this case, however, the amount of code required is reduced massively.
Pages:
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334