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 returnmay stopped early, if loop iterates resultantienumerableterminates because ofbreakor exception. - code adds collection prepares new collection in memory. code
yield returnuses existing collections make sequence can iterated, without storing result in memory. - code
yield returncan react changes in iterates during process of iteration. example, if code usesyield returnmethod adds collectionyin process of iteratingx, newly items returned when it's time iteratey. second code example not able same.
* let's pretend ienumerable<t> has add method; in reality end using list<t> or other collection.
Comments
Post a Comment