How yield
implements the pattern of lazy loading
?
Basically iterators implementated by using yield
statements are compiled into a class that implements a state machine.
If you never foreach
(=iterate over and actually use) the returned IEnumerable
, the code is never actually executed. And if you do, only the minimal code needed to determine the next value to return is executed, only to resume execution when a next value is requested.
You can actually see this behavior happening when you single step such code in the debugger. Try it at least once: I think it's illuminating to see this happen step by step.