Matthew ".NET 247" Reynolds

Matthew Reynolds... software development consultant, author, speaker and trainer

Why does a foreach(...) generate a try...finally?

Just sitting here in a session at PDC and Jan Gray who's going the “CLR: Tips and Tricks for Faster Managed Code” is doing a little trivia quiz.

I didn't know tihs, but if you decompile a foreach(...) you get a try...finally block around this.  It does this so that if the IEnumerator that is retrieved as part of the operation is disposable, the object can be properly disposed should an exception occur in the loop itself.

Comments

Jacob (.NET MVP) said:

And, at least at one time, there was a gotcha associated to this. I don't know if it's still the case, but if you have an explicit Try..Catch around a For..Each and Exit Try within the For..Each, it exits the implicit one rather than the explicit one.
# October 29, 2003 5:03 PM

RichB said:

This bug was in the VB.Net compiler.

I posted an example of it here:
http://discuss.develop.com/archives/wa.exe?A2=ind0205B&L=ADVANCED-DOTNET&P=R1276&I=-3
# October 30, 2003 5:47 AM

Ask4Soft said:

Not every foreach(..) creates a try-finally! The C# compiler translates an foreach on arrays into a normal for(i=0;...) statement!

One idea I had already is to ask the MS Guys to check if the IEnumerator of a class is IDisposable and remove the try-finally if this is not the case. For most classes this can be checked at compile time!

A valid feature request for CLR 2 or next C# version
# December 23, 2003 6:26 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)