Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact difference between returning an IEnumerable instance and the yield return statement in C#

Tags:

c#

ienumerable

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;
    }
}
like image 446
Nico Avatar asked Sep 17 '10 07:09

Nico


2 Answers

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

like image 66
Winston Smith Avatar answered Oct 26 '22 19:10

Winston Smith


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.

like image 45
tia Avatar answered Oct 26 '22 19:10

tia