Prev | Current Page 349 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

In C# 1, the iterator pattern
was directly supported from the point of view of the calling code, but not from the
perspective of the collection being iterated over. Writing a correct implementation of
IEnumerable was time-consuming and error-prone, without being interesting. In C# 2
the compiler does all the mundane work for you, building a state machine to cope
with the ???call-back??? nature of iterators.
It should be noted that iterator blocks have one aspect in common with the anonymous
methods we saw in chapter 5, even though the actual features are very different.
In both cases, extra types may be generated, and a potentially complicated code transformation
is applied to the original source. Compare this with C# 1 where most of the
transformations for syntactic sugar (lock, using, and foreach being the most obvious
examples) were quite straightforward. We??™ll see this trend toward smarter compilation
continuing with almost every aspect of C# 3.
As well as seeing a real-life example of the use of iterators, we??™ve taken a look at
how one particular library has used them in a fairly radical way that has little to do
with what comes to mind when we think about iteration over a collection. It??™s worth
bearing in mind that different languages have also looked at this sort of problem
11 Some aspects of the CCR may also become available as part of the Parallel Extensions library described in
chapter 13.


Pages:
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361