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;
    while(true)
    {
        Console.WriteLine("Inside iterator: " + i);
        yield return i;
        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:

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


Yield Keyword:
* Lazy Evaluation

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
117 Yield Keyword
127 Caching
135 Pointers
147 C# Script