jim jim - 1 year ago 164
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();

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download