tags:

views:

138

answers:

4

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;
    }
}
+1  A: 

I don't see there any relevant difference other than code bloating.

Oliver
+4  A: 

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

Winston Smith
+3  A: 

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.

tia
Even if he uses an iterator, it will still loop through the whole list before the first _yield_.
Mark Cidade
+1  A: 

There isn't any relevant difference (aside from maybe performance) between the two since you're not doing anything with the enumerator from GetIterator(). It would only make sense to re-yield if you were going to do something with the enumerator, like filter it.

Mark Cidade