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?
It seems no, while for
foreachspecification explicitly mentions ability to use duck-typing with special type(s):So you can do some magic for allocation-free
foreach.The
yeild returnspecifically requires specific return type: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.