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.
source to share