Prev | Current Page 317 | Next

Jon Skeet

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


In this chapter we??™ll look at just what is required to implement an iterator and the
support given by C# 2. As a complete example we??™ll create a useful Range class that can
be used in numerous situations, and then we??™ll explore an exciting (if slightly off-thewall)
use of the iteration syntax in a new concurrency library from Microsoft.
As in other chapters, let??™s start off by looking at why this new feature was introduced.
We??™ll implement an iterator the hard way.
6.1 C# 1: the pain of handwritten iterators
We??™ve already seen one example of an iterator implementation in section 3.4.3 when
we looked at what happens when you iterate over a generic collection. In some ways
that was harder than a real C# 1 iterator implementation would have been, because we
implemented the generic interfaces as well??”but in some ways it was easier because it
wasn??™t actually iterating over anything useful.
To put the C# 2 features into context, we??™ll first implement an iterator that is about
as simple as it can be while still providing real, useful values. Suppose we had a new type
of collection??”which can happen, even though .NET provides most of the collections
you??™ll want to use in normal applications. We??™ll implement IEnumerable so that users
of our new class can easily iterate over all the values in the collection. We??™ll ignore the
guts of the collection here and just concentrate on the iteration side.


Pages:
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329