No, you cannot do this. The compiler creates a state machine to implement yield return
, and the call code that is enumerated through your enumerated one is as much a part of its work as your code. The compiler creates a hidden object that stores the current state of your code, including its call stack and locals, and it calls different parts of your method, because the caller calls Current
and MoveNext
. Trying to list your object from the very beginning, while another enumeration is being performed, the current enumeration will be corrupted, which will not be good.
In this particular case, you also donโt want this to happen: the yield return
implementation does not save the values โโyou create, so even if you could access your own IEnumerable
on an enumeration, it will recursively call itself back several times to create each a new element, so it would take a ridiculously long time to produce even a moderate amount of primes.
source share