c# - List<T>.AddRange and the yield statement -
i aware yield keyword indicates method in appears iterator. wondering how works list<t>.addrange
.
let's use below example:
static void main() { foreach (int in myints()) { console.write(i); } } public static ienumerable<int> myints() { (int = 0; < 255; i++) { yield return i; } }
so in above example after each yield, value returned in foreach
loop in main
, printed console.
if change main
this:
static void main() { var mylist = new list<int>(); mylist.addrange(myints()); }
how work? addrange
called each int returned yield statement or somehow wait 255 values before adding entire range?
the implementation of addrange
iterate on ienumerable
input using iterator's .movenext()
method until values have been produced yield
ing method. can seen here.
so mylist.addrange(myints());
called once , implementation forces myints
return of values before moving on.
addrange
exhausts values of iterator because of how implemented, following hypothetic method evaluate first value of iterator:
public void addfirst<t>(ienumerable<t> collection) { insert(collection.first()); }
an interesting experiment while play around add console.writeline(i);
line in myints
method see when each number generated.
Comments
Post a Comment