Enumerator disposal when not using using, foreach or manually calling Dispose()

When enumerating over this iterator, if the enumerator's Dispose() is not explicitly called, and not used within a using statement, would the underlying iterator remain in an open state?

Let me re-phrase that question into a form that is easier to answer.

When using foreach to enumerate via an iterator block that contains a using statement, are the resources disposed of when control leaves the loop?

Yes.

What mechanisms ensure this?

These three:

  • A using statement is just a convenient way to write a try-finally where the finally disposes of the resource.

  • The foreach loop is also a convenient syntax for try-finally, and again, the finally calls Dispose on the enumerator when control leaves the loop.

  • The enumerator produced by an iterator block implements IDisposable. Calling Dispose() on it ensures that all the finally blocks in the iterator block are executed, including finally blocks that come from using statements.

If I avoid the foreach loop, call GetEnumerator myself, and don't call Dispose on the enumerator, do I have a guarantee that the finally blocks of the enumerator will run?

Nope. Always dispose your enumerators. They implement IDisposable for a reason.

Is that now clear?

If this subject interests you then you should read my long series on design characteristics of iterator blocks in C#.

http://blogs.msdn.com/b/ericlippert/archive/tags/iterators/