
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Dealing with Finally Blocks and Iterators
|
353
{
Console.WriteLine(s);
}
When this code is run, the following output is displayed:
String data1
String data2
...
String dataN
In iterator finally block
Move the try/finally block around the yield return statement within the iterator.
The new iterator code will look like this:
public IEnumerator GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
try
{
yield return (_items[index]);
}
finally
{
Console.WriteLine("In iterator finally block");
}
}
}
When this code is run, the following output is displayed:
String data1
In foreach finally block
String data2
In foreach finally block
...
String dataN
In foreach finally block
In iterator finally block
Discussion
You may have thought that the output would display the “In iterator finally block”
string after displaying each item in the
strSet object. However, this is not the way
that
finally blocks are handled in iterators. If you had a normal function that was
structured in exactly the same way (but did something other than a
yield return
inside the loop), you wouldn’t expect the finally block to run once per iteration.
You’d expect it to run once. Iterators go out of their way to preserve these seman-
tics. All
finally blocks inside the iterator member body are called only after the iter-
ations ...