Second, it terminates the execution of the method,
executing any appropriate finally blocks on the way out. We??™ve seen that the yield
return statement temporarily exits the method, but only until MoveNext is called
again, and we haven??™t examined the behavior of finally blocks at all yet. How can we
really stop the method, and what happens to all of those finally blocks? We??™ll start
with a fairly simple construct??”the yield break statement.
ENDING AN ITERATOR WITH YIELD BREAK
You can always find a way to make a method have a single exit point, and many people
work very hard to achieve this.3 The same techniques can be applied in iterator
blocks. However, should you wish to have an ???early out,??? the yield break statement is
your friend. This effectively terminates the iterator, making the current call to Move-
Next return false.
Listing 6.6 demonstrates this by counting up to 100 but stopping early if it runs out
of time. This also demonstrates the use of a method parameter in an iterator block,4
and proves that the name of the method is irrelevant.
static IEnumerable
CountWithTimeLimit(DateTime limit)
{
for (int i=1; i <= 100; i++)
{
if (DateTime.Now >= limit)
{
yield break;
3 I personally find that the hoops you have to jump through to achieve this often make the code much harder
to read than just having multiple return points, especially as try/finally is available for cleanup and you
need to account for the possibility of exceptions occurring anyway.
Pages:
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341