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)
All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> . You can even create your own classes that implement IEnumerable<T> , and those classes will instantly "inherit" all LINQ functionality!
In C#, an Enumerable is an object like an array, list, or any other sort of collection that implements the IEnumerable interface. Enumerables standardize looping over collections, and enables the use of LINQ query syntax, as well as other useful extension methods like List.
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:
foreach
loop, which ensures a call of Dispose()
, orwhile
loop; these iterators are disposed explicitlyusing
block, which ensures automatic disposal.In all these cases the library ensures that iterator's Dispose()
method is called upon completion.
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