DEV Community

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

Posted on

7 3

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)
    WriteLine(n);

// "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)
        infinity.Add(++i);

    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:

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay