C# Language Yield Keyword Eager evaluation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


The yield keyword allows lazy-evaluation of the collection. Forcibly loading the whole collection into memory is called eager evaluation.

The following code shows this:

IEnumerable<int> myMethod()
    for(int i=0; i <= 8675309; i++)
        yield return i;
// define the iterator
var it = myMethod.Take(3);
// force its immediate evaluation
// list will contain 0, 1, 2
var list = it.ToList();

Calling ToList, ToDictionary or ToArray will force the immediate evaluation of the enumeration, retrieving all the elements into a collection.

Got any C# Language Question?