Alternative GetEnumerator () Implementation for IEnumerable <T> Wrapper

I implemented a wrapper class for the IEnumerable<T>

same as usual and noticed that ReSharper suggested converting the loop foreach

in my method GetEnumerator

to a LINQ expression.

Out of curiosity, I clicked Convert to LINQ Expression, which then changed my method:

public IEnumerator<T> GetEnumerator()
{
    foreach (var item in _someList)
    {
        yield return item;
    }
}

      

to the ReSharper "LINQ-expression" result:

public IEnumerator<T> GetEnumerator()
{
    return ((IEnumerable<T>) _someList).GetEnumerator();
}

      


The code is pretty straight forward: instead of looping through it _someList

, it distinguishes _someList

how IEnumerable<T>

, and then uses any existing method GetEnumerator()

to return the same result.

I haven't seen this implementation before, and I'm wondering if there are any dangers to using it in situations where you really don't have anything to add to the Enumerator. I'm also wondering if there are any benefits to using one implementation over another.

+3


source to share


1 answer


If your non-generic GetEnumerator

already works great (except that it is not generic) then there is no reason not to use it. In this case, you just need to click on IEnumerable<T>

.



If not, you will need to roll your own with operators yield

, as you already know how to do.

+3


source







All Articles