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 resultantienumerable
terminates because ofbreak
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 usesyield return
method adds collectiony
in 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