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(); }
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.
No it doesn't.
// 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.
Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With