Reputation: 586
Assuming we have a specific scenario, where we want to have zero memory allocations. Is it somehow possible to use yield return (without memory allocation)?
public IEnumerable<int> GetValues()
{
yield return 42;
}
For example, I can make a struct with GetEnumerator returning struct and use it in foreach to avoid memory allocation:
(it’s possible because foreach loop actually does not use any interface constraint on the loop source. You can create a class which would work with foreach without implementing neither IEnumerable nor IEnumerable – but that’s a topic for another blog post) https://marcinjuraszek.com/2013/10/playing-around-with-listt-part-two-ienumerable-and-ienumerablet-implementation.html
Is it somehow also possible with yield return?
Upvotes: 4
Views: 891
Reputation: 141755
It seems no, while for foreach
specification explicitly mentions ability to use duck-typing with special type(s):
- Otherwise, determine whether the type
X
has an appropriateGetEnumerator
method: ....
So you can do some magic for allocation-free foreach
.
The yeild return
specifically requires specific return type:
The
yield
statement is used in an iterator block (§13.3) to yield a value to the enumerator object (§15.14.5) or enumerable object (§15.14.6) of an iterator or to signal the end of the iterator
And the actual implementation is handled by the compiler (and currently is a reference type,.so it will allocate) and AFAIK there is no way currently to intercept/substitute it.
Upvotes: 2