13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implement<strong>in</strong>giterators the easy wayThis chapter covers■ Implement<strong>in</strong>g iterators <strong>in</strong> <strong>C#</strong> 1■ Iterator blocks <strong>in</strong> <strong>C#</strong> 2■■A simple Range typeIterators as corout<strong>in</strong>esThe iterator pattern is an example of a behavioral pattern—a design pattern thatsimplifies communication between objects. It’s one of the simplest patterns tounderstand, and <strong>in</strong>credibly easy to use. In essence, it allows you to access all theelements <strong>in</strong> a sequence of items without car<strong>in</strong>g about what k<strong>in</strong>d of sequence it is—an array, a list, a l<strong>in</strong>ked list, or none of the above. This can be very effective forbuild<strong>in</strong>g a data pipel<strong>in</strong>e, where an item of data enters the pipel<strong>in</strong>e and goes througha number of different transformations or filters before com<strong>in</strong>g out at the otherend. Indeed, this is one of the core patterns of LINQ, as we’ll see <strong>in</strong> part 3.In .NET, the iterator pattern is encapsulated by the IEnumerator and IEnumerable<strong>in</strong>terfaces and their generic equivalents. (The nam<strong>in</strong>g is unfortunate—the patternis normally called iteration rather than enumeration to avoid gett<strong>in</strong>g confused with161Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!