Possible Duplicate:
C# – Proper Use of yield return
What can be a real use case for C# yield?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you want deferred execution.
This makes sense in most cases where the alternative is to construct a temporary collection.
Consider this scenario: I have a list of integers and I want to list their squares.
I could do this:
Then I could sum the squares, take their average, find the greatest, etc.
But I really didn’t need to populate a whole new
List<int>for that purpose. I could’ve usedyieldto enumerate over the initial list and return the squares one-by-one:The fact that this actually makes a difference might not be apparent until you start dealing with very large collections, where populating temporary collections proves to be quite wasteful.
For example suppose I wanted to find the first square above a certain threshold. I could do this:
But if my
Squaresmethod populated an entireList<int>before returning, the above code would be doing potentially far more work than necessary.