Alex Rivera | Logout

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

Asked 2009-07-06T18:11:21.723
90

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?

Edit
Report

2 Answers

2

If the entire list is gigantic, it might eat a lot of memory just to sit around, whereas with the yield you only play with what you need, when you need it, regardless of how many items there are.

answered 2009-07-06T18:17:22.303
2

Using the yield return you can iterate over items without ever having to build a list. If you don't need the list, but want to iterate over some set of items it can be easier to write

foreach (var foo in GetSomeFoos()) {
    operate on foo
}

Than

foreach (var foo in AllFoos) {
    if (some case where we do want to operate on foo) {
        operate on foo
    } else if (another case) {
        operate on foo
    }
}

You can put all of the logic for determining whether or not you want to operate on foo inside your method using yield returns and you foreach loop can be much more concise.

answered 2009-07-06T18:22:14.977

Your Answer