What can be a real use case for C# yield?
Thanks.
Answer
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:
public static IEnumerable Squares(this IEnumerable numbers) {
List squares = new List();
foreach (int number in numbers)
squares.Add(number * number);
return squares;
}
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
for that purpose. I could've used yield
to enumerate over the initial list and return the squares one-by-one:
public static IEnumerable Squares(this IEnumerable numbers) {
foreach (int number in numbers)
yield return number * number;
}
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:
IEnumerable numbers = GetLotsOfNumbers();
var squares = numbers.Squares();
int firstBigSquare = squares
.Where(x => x >= 1000)
.FirstOrDefault();
But if my Squares
method populated an entire List
before returning, the above code would be doing potentially far more work than necessary.
No comments:
Post a Comment