Currently I'm working with some libraries applying deferred execution via iterators. In some situations I have the need to "forward" the recieved iterator simply. I.e. I have to get the IEnumerable<T>
instance from the called method and return it immediately.
Now my question: Is there a relevant difference between simply returning the recieved IEnumerable<T>
or re-yielding it via a loop?
IEnumerable<int> GetByReturn()
{
return GetIterator(); // GetIterator() returns IEnumerable<int>
}
// or:
IEnumerable<int> GetByReYielding()
{
for(var item in GetIterator()) // GetIterator() returns IEnumerable<int>
{
yield return item;
}
}
It may be worth your while reading Jon Skeet's article on C# Iterators. It's quite informative.
http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx
They ARE different. For example, if the GetIterator()
declared as:
IEnumerable<int> GetIterator() {
List<int> result = new List<int>();
for(int i = 0; i < 1000; i++) {
result.Add(i);
}
return result;
}
If you do not do re-yielding, the GetIterator()
and the loop got executed immediately. Therefore, the answer depends on how you implement GetIterator()
. If it is certain that GetIterator()
will be yielding, so there is no point re-yielding it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With