In this blog series, you will learn how to implement lazy evaluation with the yield keyword and be introduced to Microsoft's Reactive Extensions (Rx) for complex event processing (CEP) and other goodness.
First off, what are the main differences between IEnumerable, ICollection & IList?
- IEnumerable is a potentially infinite sequence, 1, 2, 3, ...
- ICollection is a finite sequence, 1, 2, 3, ..., n
- IList preserves order so you can index into it, list[5]
IList extends ICollection which extends IEnumerable. We're interested in IEnumerable.
A well known but not well understood gem of C# is the yield keyword. Let's look at an example.
But what yield does, and this is where the goodness is, is it wont execute the AllWholeNumbers() method until you access the next element of list. It's best to see this with a debugger - it wont step into the method until the first iteration of the foreach loop.
Once yield is hit the first time, AllWholeNumbers() runs until 0 is returned (given to the variable result) and the method is put into hibernation. In other words, the method's internal state is saved for later. The second iteration of the foreach loop will restore this state and start from where it left off - incrementing idx. It will then return 1, hibernate, return 2, hibernate, and so on.
So you can do things like,
And it will only execute what it needs to to get the results.
It's interesting to note that while AllWholeNumbers() appears to be an infinite loop, it's a mathematically valid representation of the whole numbers (all infinitely many of them) and, thanks to the yield keyword, it can be used without waiting forever.
Next post: Implementing Lazy Evaluation - Part 2
No comments:
Post a Comment