Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is Dispose() of a class implementing IEnumerator<T> called automatically by Linq?

I’m studying IEnumerable<T> and IEnumerator<T>.

I wrote the code referring to this example.

Here’s a part of the example code in the link that uses it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var stringsFound =
    from line in new StreamReaderEnumerable(@"C:\temp\tempFile.txt")
    where line.Contains("string to search for")
    select line;

Console.WriteLine($"Found : {stringsFound.Count()}");

I have a question for you here.

StreamReaderEnumerator is created automatically by the system, so when is StreamReaderEnumerator‘s Dispose() called?

>Solution :

None of your code creates any enumerators that you are responsible for disposing of. LINQ operators like Count are designed so that they create and dispose the enumerators internally, so you don’t have to worry about it at all.

You can see the reference source for Count here, and you’ll find the snippet:

int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
{
    checked
    {
        while (e.MoveNext())
        {
            count++;
        }
    }
}

return count;

The using statement already disposes the enumerator for you – Dispose is called, before Count even returns. There’s nothing for you to do.

Of course, if you are consuming stringsFound by getting its enumerator (though it’s very rare that you’d need to do it this way), you do need to remember to dispose it.

var stringsFoundEnumerator = stringsFound.GetEnumerator();
//  ^^^^^^ remember to dispose this!

Side note: foreach loops translates to while loops wrapped by a using statement, so you don’t need to worry about disposing the enumerator if you are iterating over stringsFound with a foreach loop either. 😀

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading