bhylu.com

Advertisements

C# Deferred Execution

Observe a deferred query after source mutation and compare it with a materialized earlier result.

How it works

Many IEnumerable-based LINQ operations defer execution until enumeration. Creating a query object therefore does not necessarily read all its data immediately. Enumerating twice can repeat work or observe a changed source. Materialize once when the application needs a stable snapshot, accepting the memory and timing tradeoff. A provider-backed sequence can also issue remote work on each enumeration, so a short variable declaration is not evidence that expensive work happened only once.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;
using System.Linq;
using System.Collections.Generic;

internal static class Program
{
    private static void Main(string[] args)
    {
        var source = new List<int> { 2, 4 };
        var query = source.Where(value => value >= 3);
        int[] snapshot = query.ToArray();
        source.Add(6);
        Console.WriteLine($"Snapshot: {string.Join(",", snapshot)}");
        Console.WriteLine($"Later query: {string.Join(",", query)}");
    }
}

Expected result

Snapshot: 4
Later query: 4,6

The snapshot was built before six was added, while the later enumeration sees the new source state. This program mutates between enumerations, not during an active foreach. Keep predicates free from surprising side effects; deferred and repeated execution can otherwise make logging or external writes happen an unexpected number of times.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.