Does foreach automatically call Dispose?

jim picture jim · Feb 13, 2011 · Viewed 13.4k times · Source

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();
}

Answer

Matt H picture Matt H · Feb 13, 2011

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