DEV Community

Cover image for Explaining lazy evaluation in C#
Talles L
Talles L

Posted on

Explaining lazy evaluation in C#

Countless were the times I've fired up Visual Studio to write the following example explaining what lazy evaluation is and why it's better to expose collections as IEnumerable<T>:

using System.Collections.Generic;
using System.Linq;
using static System.Console;

// If you replace the lazy call below with the eager one you get an out of memory error
var oneToTen = LazyInfinity().Take(10);

foreach (var n in oneToTen)

// "In eager evaluation, the first call to the iterator will result in the entire collection being processed."
// "A temporary copy of the source collection might also be required."
static IEnumerable<int> EagerInfinity()
    var i = 0;
    var infinity = new List<int>();

    while (true)

    return infinity;

// "In lazy evaluation, a single element of the source collection is processed during each call to the iterator."
static IEnumerable<int> LazyInfinity()
    var i = 0;

    while (true)
        yield return ++i;
Enter fullscreen mode Exit fullscreen mode

More at:

Top comments (0)