Lazy Evaluation

suggest change

Only when the foreach statement moves to the next item does the iterator block evaluate up to the next yield statement.

Consider the following example:

private IEnumerable<int> Integers()
    var i = 0;
        Console.WriteLine("Inside iterator: " + i);
        yield return i;

private void PrintNumbers()
    var numbers = Integers().Take(3);
    Console.WriteLine("Starting iteration");

    foreach(var number in numbers)
        Console.WriteLine("Inside foreach: " + number);

This will output:

Starting iteration Inside iterator: 0 Inside foreach: 0 Inside iterator: 1 Inside foreach: 1 Inside iterator: 2 Inside foreach: 2

View Demo

As a consequence:

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents