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.

1 Comment

  • 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.

Comments have been disabled for this content.