Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata