Can someone please explain this lazy evaluation code?
Posted
by Tejs
on Stack Overflow
See other posts from Stack Overflow
or by Tejs
Published on 2010-04-29T19:14:27Z
Indexed on
2010/04/29
19:27 UTC
Read the original article
Hit count: 603
So, this question was just asked on SO:
http://stackoverflow.com/questions/2740001/how-to-handle-an-infinite-ienumerable
My sample code:
public static void Main(string[] args)
{
foreach (var item in Numbers().Take(10))
Console.WriteLine(item);
Console.ReadKey();
}
public static IEnumerable<int> Numbers()
{
int x = 0;
while (true)
yield return x++;
}
Can someone please explain why this is lazy evaluated? I've looked up this code in Reflector, and I'm more confused than when I began.
Reflector outputs:
public static IEnumerable<int> Numbers()
{
return new <Numbers>d__0(-2);
}
For the numbers method, and looks to have generated a new type for that expression:
[DebuggerHidden]
public <Numbers>d__0(int <>1__state)
{
this.<>1__state = <>1__state;
this.<>l__initialThreadId = Thread.CurrentThread.ManagedThreadId;
}
This makes no sense to me. I would have assumed it was an infinite loop until I put that code together and executed it myself.
© Stack Overflow or respective owner