Does foreach automatically call Dispose?
In C#, Does foreach automatically call Dispose on any object implementing IDisposable?
http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx seems to indicate that it does:
*Otherwise, the collection expression is of a type that implements System.IEnumerable, and the expansion of the foreach statement is: Copy
IEnumerator enumerator =
((System.Collections.IEnumerable)(collection)).GetEnumerator();
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
statement;
}
}
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();
}
Solution 1:
Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.
Solution 2:
This question / answer is poorly worded.
It is not clear if the question asked is:
Q: "Does foreach dispose objects returned by the enumerator before moving to the next?"
A: The answer is of course, NO. It does nothing except provide a convenient way to run some code once for each object in an enumeration.
Or whether it means:
Q: "Under the hood, foreach uses an enumerable object. Does this get disposed after the call to foreach, even if there's an exception in the iterator block?"
A: The answer is (still fairly obviously) YES! Since the syntax does not provide you access to the enumerator, it has the responsibility to dispose it.
The answer to the second question is where the confusion arises, since people have heard that foreach expands to a while block with a try/finally block. The purpose of that finally is to ensure that the enumerator is disposed if it implements IDisposable.
In case you need to see it for yourself: See it in action here
Hope this helps clarify! ;)