Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); } 
like image 391
jim Avatar asked Feb 13 '11 04:02

jim


People also ask

Is dispose called automatically?

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.

Does using always call Dispose?

No it doesn't.

When the Dispose method is called?

// If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. private void Dispose(bool disposing) { // Check to see if Dispose has already been called.


1 Answers

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

like image 94
Matt H Avatar answered Sep 21 '22 17:09

Matt H