Lazy Evaluation Example C# with Example
using System.Numerics; // also add reference to System.Numberics
private static IEnumerable Fibonacci()
BigInteger prev = 0;
BigInteger current = 1;
yield return current;
var next = prev + current;
prev = current;
current = next;
static void Main()
// print Fibonacci numbers from 10001 to 10010
var numbers = Fibonacci().Skip(10000).Take(10).ToArray();
How it works under the hood (I recommend to decompile resulting .exe ﬁle in IL Disaambler tool):
1. C# compiler generates a class implementing IEnumerable and IEnumerator
(d 0 in ildasm).
2. This class implements a state machine. State consists of current position in method and values of local
3. The most interesting code are in bool IEnumerator.MoveNext() method. Basically, what MoveNext() do:
Restores current state. Variables like prev and current become ﬁelds in our class (5 2 and
5 1 in ildasm). In our method we have two positions (<>1 state): ﬁrst at the opening curly
brace, second at yield return.
Executes code until next yield return or yield break/}.
For yield return resulting value is saved, so Current property can return it. true is returned. At this
point current state is saved again for the next MoveNext invocation.
For yield break/} method just returns false meaning iteration is done.
Also note, that 10001th number is 468 bytes long. State machine only saves current and prev variables as ﬁelds.
While if we would like to save all numbers in the sequence from the ﬁrst to the 10000th, the consumed memory
size will be over 4 megabytes. So lazy evaluation, if properly used, can reduce memory footprint in some cases.