c# - Translating yield returns in nested loops -


i learning basic c# have following code snippet

while(p!=null) {    foreach(var x in x)       yield return x;    //....    foreach(var y in y)       yield return y;    p=getp(); } 

is code above same as

ienumerable<object> os; while (p!=null) {       foreach(var x in x)       os.add(x);    //....    foreach(var y in y)       os.add(y);    p=getp(); } return os; 

???

the 2 code snippets* "the same" in sense produce same sequence of objects if iteration carried out completion. however, actual sequence of going happen during iteration different.

  • code yield return may stopped early, if loop iterates resultant ienumerable terminates because of break or exception.
  • code adds collection prepares new collection in memory. code yield return uses existing collections make sequence can iterated, without storing result in memory.
  • code yield return can react changes in iterates during process of iteration. example, if code uses yield return method adds collection y in process of iterating x, newly items returned when it's time iterate y. second code example not able same.

* let's pretend ienumerable<t> has add method; in reality end using list<t> or other collection.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -