Search code examples
c#iteratoryield-return

What is the purpose/advantage of using yield return iterators in C#?


All of the examples I've seen of using yield return x; inside a C# method could be done in the same way by just returning the whole list. In those cases, is there any benefit or advantage in using the yield return syntax vs. returning the list?

Also, in what types of scenarios would yield return be used that you couldn't just return the complete list?


Solution

  • But what if you were building a collection yourself?

    In general, iterators can be used to lazily generate a sequence of objects. For example Enumerable.Range method does not have any kind of collection internally. It just generates the next number on demand. There are many uses to this lazy sequence generation using a state machine. Most of them are covered under functional programming concepts.

    In my opinion, if you are looking at iterators just as a way to enumerate through a collection (it's just one of the simplest use cases), you're going the wrong way. As I said, iterators are means for returning sequences. The sequence might even be infinite. There would be no way to return a list with infinite length and use the first 100 items. It has to be lazy sometimes. Returning a collection is considerably different from returning a collection generator (which is what an iterator is). It's comparing apples to oranges.

    Hypothetical example:

    static IEnumerable<int> GetPrimeNumbers() {
       for (int num = 2; ; ++num) 
           if (IsPrime(num))
               yield return num;
    }
    
    static void Main() { 
       foreach (var i in GetPrimeNumbers()) 
           if (i < 10000)
               Console.WriteLine(i);
           else
               break;
    }
    

    This example prints prime numbers less than 10000. You can easily change it to print numbers less than a million without touching the prime number generation algorithm at all. In this example, you can't return a list of all prime numbers because the sequence is infinite and the consumer doesn't even know how many items it wants from the start.