Deferred execution
Deferred execution
Deferred execution means defining a query does not necessarily read its elements yet. LINQ to Objects operators such as Where and Select generally read the source when the result is enumerated. Materializing a result with ToArray or ToList captures the result membership at that moment.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Define now, read later
An IEnumerable<T> query represents an enumeration recipe. Where does not immediately traverse the list when the query is created, although argument validation may occur immediately. Modifying the list before enumeration changes what this query sees.
using System;using System.Collections.Generic;using System.Linq;var stock = new List<int> { 1, 4 };var query = stock.Where(n => n >= 3);stock.Add(6);Console.WriteLine(string.Join(",", query));stock.Remove(4);Console.WriteLine(string.Join(",", query));The first traversal sees the added 6; the second reads the changed list. The query did not retain the earlier result.
Expected output (reasoned, not executed):
4,66Materialize when a stable result is needed
ToList and ToArray enumerate the source now. They create new collection storage, not a deep copy of referenced objects. Count and Sum are immediate scalar operations. Avoid collecting everything when only one match is needed.
using System;using System.Collections.Generic;using System.Linq;var stock = new List<int> { 2, 4 };var query = stock.Where(n => n >= 3);var snapshot = query.ToArray();stock.Add(8);Console.WriteLine(string.Join(",", snapshot));Console.WriteLine(string.Join(",", query.ToList()));Console.WriteLine(query.Count());The array has membership from materialization time; later ToList and Count see current membership.
Expected output (reasoned, not executed):
44,82Recognize repeated work and buffering
A deferred query can execute a predicate again on each enumeration. Where can stream results one by one, whereas OrderBy must establish ordering before yielding sorted results in ordinary enumeration. Some terminal operators optimize traversal, so do not depend on side-effect counts in general query code. The instrumented foreach demonstration below intentionally exposes evaluation.
using System;using System.Linq;int calls = 0;var query = new[] { 1, 2, 3 }.Where(n => { calls++; return n > 1; });Console.WriteLine(calls);foreach (int n in query) Console.WriteLine(n);Console.WriteLine(calls);foreach (int n in query) Console.WriteLine(n);Console.WriteLine(calls);Creating the query does not invoke the predicate. Each full foreach checks all three source values. In production, prefer pure predicates without hidden side effects.
Expected output (reasoned, not executed):
0233236Common mistakes and edge cases
A deferred query is not automatically cached. Do not mutate a List<T> while enumerating it; its enumerator normally detects structural changes and throws. ToArray and ToList only copy references for reference-type elements. Deferred is not synonymous with streaming: sorting and grouping may buffer substantial data. Avoid materializing unbounded sequences. Database providers can translate queries differently and may execute remote work; this chapter is strictly LINQ to Objects.
Practice and recap
Create a query over [1,5,7] selecting values above 4. Materialize a snapshot; add 9, then compare the snapshot, the deferred query and its Sum. Remove 5 and repeat.
Hint: Use ToArray before mutating, then enumerate the original query after each mutation.
Learning objective: Explain when a query reads its source. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Deferred execution — knowledge check
Apply the lesson concepts to the following scenarios.
When does Where normally evaluate its predicate?
What does ToArray do?
Can repeated enumeration execute a predicate twice for one source element?
Which operator typically buffers for ordering?
Why avoid side effects inside LINQ predicates?