Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the using statement work on IEnumerator and what does it do?

Back when I was learning about foreach, I read somewhere that this:

foreach (var element in enumerable)
{
    // do something with element
}

is basically equivalent to this:

using (var enumerator = enumerable.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;

        // do something with element
    }
}

Why does this code even compile if neither IEnumerator nor IEnumerator<T> implement IDisposable? C# language specification only seems to mention the using statement in the context of IDisposable.

What does such an using statement do?

like image 713
relatively_random Avatar asked Mar 22 '17 13:03

relatively_random


2 Answers

Please, check the following link about foreach statement. It uses try/finally block with Dispose call if it's possible. That's the code which is behind using statement.

like image 79
ilya korover Avatar answered Sep 28 '22 07:09

ilya korover


IEnumerator may not implement IDisposable but GetEnumerator() returns a IEnumerator<T> which does. From the docs on IEnumerator<T>:

In addition, IEnumerator implements IDisposable, which requires you to implement the Dispose method. This enables you to close database connections or release file handles or similar operations when using other resources. If there are no additional resources to dispose of, provide an empty Dispose implementation.

This is of course assuming that your enumeration is an IEnumerable<T> and not just a IEnumerable. If your original enumeration was just an IEnumerable then it wouldn't compile.

like image 31
DavidG Avatar answered Sep 28 '22 09:09

DavidG