A trivial example of an “infinite” IEnumerable would be
IEnumerable<int> Numbers() {
int i=0;
while(true) {
yield return unchecked(i++);
}
}
I know, that
foreach(int i in Numbers().Take(10)) {
Console.WriteLine(i);
}
and
var q = Numbers();
foreach(int i in q.Take(10)) {
Console.WriteLine(i);
}
both work fine (and print out the number 0-9).
But are there any pitfalls when copying or handling expressions like q? Can I rely on the fact, that they are always evaluated “lazy”? Is there any danger to produce an infinite loop?
Yes, you are guaranteed that the code above will be executed lazily. While it looks (in your code) like you’d loop forever, your code actually produces something like this:
(This obviously isn’t exactly what will be generated, since this is pretty specific to your code, but it’s nonetheless similar and should show you why it’s going to be lazily evaluated).