The behavior of Current is odd??”in particular, keeping hold of the last item after
supposedly moving off it could keep it from being garbage collected. It??™s possible that
this may be fixed in a later release of the C# compiler, though it??™s unlikely as it could
break existing code.6 Strictly speaking, it??™s correct from the C# 2 language specification
point of view??”the behavior of the Current property is undefined. It would be
nicer if it implemented the property in the way that the framework documentation
suggests, however, throwing exceptions at appropriate times.
So, there are a few tiny drawbacks from using the autogenerated code, but sensible
callers won??™t have any problems??”and let??™s face it, we??™ve saved a lot of code in order to
come up with the implementation. This means it makes sense to use iterators more
widely than we might have done in C# 1. Our next section provides some sample code
so you can check your understanding of iterator blocks and see how they??™re useful in
real life rather than just in theoretical scenarios.
6.3 Real-life example: iterating over ranges
Have you ever written some code that is really simple in itself but makes your project
much neater? It happens to me every so often, and it usually makes me happier than it
probably ought to??”enough to get strange looks from colleagues, anyway. That sort of
slightly childish delight is particularly strong when it comes to using a new language
feature in a way that is clearly nicer and not just doing it for the sake of playing with
new toys.
Pages:
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347