Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do LINQ IEnumerable extensions call Dispose on their IEnumerable?

Tags:

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)

like image 225
humanoidanalog Avatar asked Aug 11 '15 01:08

humanoidanalog


People also ask

Does LINQ work with IEnumerable?

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!

What are enumerables in c#?

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.


1 Answers

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.

like image 188
Sergey Kalinichenko Avatar answered Sep 28 '22 09:09

Sergey Kalinichenko