How to handle an "infinite" IEnumerable?
Posted
by Danvil
on Stack Overflow
See other posts from Stack Overflow
or by Danvil
Published on 2010-04-29T19:00:20Z
Indexed on
2010/04/29
19:07 UTC
Read the original article
Hit count: 307
A trivial example of an "infinite" IEnumerable would be
IEnumerable<int> Numbers() {
int i=0;
while(true) {
yield return 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?
© Stack Overflow or respective owner