We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Strapontin • 1 year ago

So the yield return is only used in order to reduce code length ?

Anonymous • 1 year ago

no - the control flow is different.
When GetFruits() is called, the entire list of fruits is searched before returning two results to the calling Main method.
When GetFruitsWithYield is called, control is returned to the Main method each time a result is yielded, then the next time the loop runs, the GetFruitsWithYield method picks up where it left of in the list of plants.

So in this case GetFruits() will not return control to main until it checks all 4 plants and will return the two matching results : ["Apple", "Pear"].
GetFruitsWithYield() however, will check the first plant in _plants, and since the test is true it will yield return "Apple" to Main (it will yield control back to Main and return the value of "Apple". With a value for fruit now defined, Main will output the "Apple" to the console. Now the loop in main runs again and it will re-enter GetFruitsWithYield() and remember where it left off so it will begin by checking the second item in _plants ("Pear") and will yield control back to Main returning "Pear" since the test is true.

So, yield return returns values back to the caller one at a time, but remembers where it left off each time it re-enters from a loop.