22

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)

6
  • 5
    You need not to about dispose as by John Skeet reply ....[Link][1] [1]: stackoverflow.com/questions/13459447/… Commented Aug 11, 2015 at 1:17
  • If you want to be sure, you could always put a Console.WriteLine() in your Dispose() and see if it gets fired. Commented Aug 11, 2015 at 1:29
  • 1
    If his MyClass implements IDisposable the Dispose() method would get called. The garbage collector isn't the one that calls Dispose(). Commented Aug 11, 2015 at 1:33
  • @MattRowland - That's not right about MyClass. In the OP's code .Dispose would not be called on the new MyClass(). Commented Aug 11, 2015 at 1: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. Commented Aug 11, 2015 at 1:46

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So only in the case of foreach is Dispose called automatically 'on enumeration'?
@user2864740 Yes. If you use Iterator<T> manually from inside a for or a while, you should call Dispose() yourself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.