0Pricing
C# Academy · Lesson

Lazy Evaluation Semantics

Understand deferred execution of iterators.

Deferred Execution

Iterators and LINQ queries use deferred execution: defining the query does almost nothing. The work only happens when you actually enumerate the result, item by item.

Nothing Runs Until You Enumerate

Calling an iterator method does not run its body. The body starts executing only when a foreach (or another consumer) pulls the first value.

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> Numbers()
    {
        Console.WriteLine("-- iterator body started --");
        yield return 1;
        yield return 2;
    }

    public static void Main()
    {
        var seq = Numbers();
        Console.WriteLine("query created, body not run yet");
        foreach (var n in seq) Console.WriteLine(n);
    }
}

All lessons in this course

  1. Iterator Methods with yield return
  2. yield break and Early Termination
  3. Lazy Evaluation Semantics
  4. Custom Enumerables
← Back to C# Academy