Prev | Current Page 316 | Next

Jon Skeet

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

Indeed, this is one of the core patterns of LINQ, as we??™ll see in part 3.
In .NET, the iterator pattern is encapsulated by the IEnumerator and IEnumerable
interfaces and their generic equivalents. (The naming is unfortunate??”the pattern
is normally called iteration rather than enumeration to avoid getting confused with
This chapter covers
?–  Implementing iterators in C# 1
?–  Iterator blocks in C# 2
?–  A simple Range type
?–  Iterators as coroutines
162 CHAPTER 6 Implementing iterators the easy way
other meanings of the word enumeration. I??™ve used iterator and iterable throughout this
chapter.) If a type implements IEnumerable, that means it can be iterated over; calling
the GetEnumerator method will return the IEnumerator implementation, which is the
iterator itself.
As a language, C# 1 has built-in support for consuming iterators using the foreach
statement. This makes it incredibly easy to iterate over collections??”easier than using
a straight for loop??”and is nicely expressive. The foreach statement compiles down
to calls to the GetEnumerator and MoveNext methods and the Current property, with
support for disposing the iterator afterwards if IDisposable has been implemented.
It??™s a small but useful piece of syntactic sugar.
In C# 1, however, implementing an iterator is a relatively difficult task. The syntactic
sugar provided by C# 2 makes this much simpler, which can sometimes lead to the iterator
pattern being worth implementing in cases where otherwise it would have caused
more work than it saved.


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