Why can\'t we use both return and yield return in the same method?
For example, we can have GetIntegers1 and GetIntegers2 below, but not GetIntegers3.
pu
I think the main reason why it doesn't work is because designing it in a way that is not overcomplicated but is performant at the same time would be hard, with relatively little benefit.
What exactly would your code do? Would it directly return the array, or would it iterate over it?
If it would directly return the array, then you would have to think up complicated rules under what conditions is return
allowed, because return
after yield return
doesn't make sense. And you would probably need to generate complicated code to decide, whether the method will return custom iterator or the array.
If you wanted to iterate the collection, you probably want some better keyword. Something like yield foreach. That was actually considered, but was ultimately not implemented. I think I remember reading the main reason is that it's actually really hard to make it perform well, if you have several nested iterators.