20

Given I've written a class that implements IEnumerable, and returns an IEnumerator that's not just IDisposable by nature of being an enumerator, but from having managed resources that it needs to Dispose() after it's done enumerating, can I trust that the following will Dispose() those managed resources as long as my enumerator properly disposes those managed resources in its IDisposable implementation?

return (new MyClass()).Select(x => x);

EDIT: This question is seemingly similar to the one mods marked similar to it, but it's semantically different IMO (I saw it before I made the question)

humanoidanalog
  • 313
  • 1
  • 7
  • 5
    You need not to about dispose as by John Skeet reply ....[Link][1] [1]: http://stackoverflow.com/questions/13459447/do-i-need-to-consider-disposing-of-any-ienumerablet-i-use – Janty Aug 11 '15 at 01:17
  • If you want to be sure, you could always put a `Console.WriteLine()` in your `Dispose()` and see if it gets fired. – Matt Rowland Aug 11 '15 at 01:29
  • 1
    If his `MyClass` implements `IDisposable` the `Dispose()` method would get called. The garbage collector isn't the one that calls `Dispose()`. – Matt Rowland Aug 11 '15 at 01:33
  • @MattRowland - That's not right about `MyClass`. In the OP's code `.Dispose` **would not** be called on the `new MyClass()`. – Enigmativity Aug 11 '15 at 01:44
  • 1
    I wasn't saying that it would. I was saying that he could check to see if it would by placing a `Console.WriteLine()` in the `Dispose()` method. – Matt Rowland Aug 11 '15 at 01:46
  • I checked of course for this single method, but I wanted to know if this is something I could assume for any LINQ enumeration. Matt is right in that `Dispose()` isn't called from garbage collection. Hence, "managed resources" – humanoidanalog Aug 11 '15 at 18:07

1 Answers1

12

Yes, you can rely on the call of Dispose() on your iterators from inside the methods of LINQ.

In the reference code published by Microsoft, the use of iterators falls in three categories:

  • Iterators are used from within a foreach loop, which ensures a call of Dispose(), or
  • Iterators are used in conjunction with a while loop; these iterators are disposed explicitly
  • Iterators are obtained inside a using block, which ensures automatic disposal.

In all these cases the library ensures that iterator's Dispose() method is called upon completion.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523