Prev | Current Page 324 | Next

Jon Skeet

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


No normal return statements are allowed within iterator blocks??”only yield
return. All yield return statements in the block have to try to return a value compatible
with the yield type of the block. To use our previous example, you couldn??™t write
yield return 1; in a method declared to return IEnumerable.
NOTE Restrictions on yield return??”There are a few further restrictions on yield
statements. You can??™t use yield return inside a try block if it has any
catch blocks, and you can??™t use either yield return or yield break
(which we??™ll come to shortly) in a finally block. That doesn??™t mean you
can??™t use try/catch or try/finally blocks inside iterators??”it just
restricts what you can do in them.
The big idea that you need to get your head around when it comes to
iterator blocks is that although you??™ve written a method that looks like it
executes sequentially, what you??™ve actually asked the compiler to do is
create a state machine for you. This is necessary for exactly the same reason
we had to put so much effort into implementing the iterator in
C#1??”the caller only wants to see one element at a time, so we need to
keep track of what we were doing when we last returned a value.
In iterator blocks, the compiler creates a state machine (in the form of a
nested type), which remembers exactly where we were within the block and what values
the local variables (including parameters) had at that point.


Pages:
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336