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:

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay