
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
352
|
Chapter 6: Iterators and Partial Types
See Also
See Recipe 6.9; see the “Iterators,” “yield,” “IEnumerator Interface,” and “IEnumera-
ble Interface” topics in the MSDN documentation.
6.9 Dealing with Finally Blocks and Iterators
Problem
You have added a try/finally block to your iterator and you notice that the finally
block is not being executed when you think it should.
Solution
Wrap a try block around the iteration code in the GetEnumerator iterator with a
finally block following this try block:
public class StringSet
{
private List<string> _items = new List<string>( );
public void AddString(string str)
{
_items.Add(str);
}
public IEnumerator GetEnumerator( )
{
try
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
finally
{
Console.WriteLine("In iterator finally block");
}
}
}
The foreach code that calls this iterator looks like this:
// Create a new StringSet object.
StringSet strSet = new StringSet( );
// Store string data in the strSet object...
// Use the GetEnumerator iterator.
foreach (string s in strSet)