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

Time:08-02

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:

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?

CodePudding user response:

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. :D

  • Related