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

When I found out about foreach

, I read this somewhere:

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 IEnumerator

neither IEnumerator<T>

does it implement IDisposable

? The C # language specification only mentions the operator using

in context IDisposable

.

What does such an operator using

do?

+3


source to share


2 answers


Please check the link in the foreach statement . It uses a try / finally block with a call to Dispose if possible. This is the code behind using the operator .



+4


source


IEnumerator

may not implement IDisposable

, but GetEnumerator()

returns IEnumerator<T>

, which does. From the docs IEnumerator<T>

:

In addition, IEnumerator implements IDisposable, which requires implementing the Dispose method. This allows you to close database connections or unlock files or similar operations while using other resources. If there are no additional resources for disposal, provide an empty implementation of Dispose.



This, of course, assumes that your enum is this IEnumerable<T>

and not just IEnumerable

. If the original enum was only IEnumerable

, then it won't compile.

+2


source







All Articles