jim jim - 4 months ago 54
C# Question

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:

IEnumerator enumerator =
try {
while (enumerator.MoveNext()) {
ElementType element = (ElementType)enumerator.Current;
finally {
IDisposable disposable = enumerator as System.IDisposable;
if (disposable != null) disposable.Dispose();


Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.