In C#, a LINQ Where lambda captures a local minTotal that is reassigned before the foreach; which value filters, and why does a bad row throw inside the foreach?
answer
- captured variable, not value
- the lambda runs during MoveNext
- argument checks are not deferred
- copy or materialise to pin it
basics
~20 sThe reassigned value filters: the lambda captures the variable minTotal and reads it whenever the predicate runs, which is during enumeration. For the same reason a FormatException from decimal.Parse in the lambda surfaces in the foreach, not at Where.
solid answer
~40 sC# lambdas capture **variables, not values**: the compiler moves `minTotal` into a closure object shared by the method and the lambda, and `Where` stores the delegate. The predicate runs only when the `foreach` calls `MoveNext`, so it reads whatever `minTotal` holds then, 300 rather than 100. Exceptions follow the same clock: `decimal.Parse` failing on "n/a" throws `FormatException` from inside the `foreach`, and a `try` around the line that builds the query catches nothing. Argument validation is the exception to deferral: `Where` on a null source throws `ArgumentNullException` at the call. To pin a threshold, copy it into a local that is never reassigned before building the query, or materialise with `ToList()` inside the `try`.
code
csharp · 29 linesvar orders = new List<Order> { new(1, "250"), new(2, "500"), new(3, "n/a") };
decimal minTotal = 100m;
var large = orders.Where(o => decimal.Parse(o.Total) >= minTotal);
Console.WriteLine("Query built, nothing parsed yet");
minTotal = 300m; // changed after the query was built
try
{
foreach (var o in large)
Console.WriteLine($"Order {o.Id}");
}
catch (FormatException ex)
{
Console.WriteLine($"Thrown inside foreach: {ex.GetType().Name}");
}
try
{
IEnumerable<Order>? missing = null;
var q = missing!.Where(o => true); // argument checks are not deferred
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"Thrown at Where itself: {ex.ParamName}");
}
record Order(int Id, string Total);go deeper
Recall that a lambda inside Where runs when the query is looped over, so it sees variables as they are at that moment.
Explain capture by variable through a closure object, and why predicate exceptions appear in foreach or ToList rather than at the Where call.
Debug a filter that used the wrong threshold or threw far from its source, then fix it by copying the value or materialising inside the right try block.
Set expectations for code that returns deferred queries across layers, since every captured value and failure then belongs to whoever enumerates later.
## Capturing a variable, not a value When a lambda uses a local variable of the enclosing method, C# does not copy the variable's current value into the lambda. It **captures the variable itself**: the compiler moves the local into a compiler-generated closure object, and both the method body and the lambda read and write that one field. Any assignment the method makes after creating the lambda is visible to the lambda the next time it runs. With most lambdas this rarely surprises anyone, because they run straight away. A LINQ to Objects query is different: `Where` **stores** the predicate and runs it later, during enumeration. The gap between building the query and enumerating it is exactly where a reassignment can slip in. ## Reading the example The example below builds `orders.Where(o => decimal.Parse(o.Total) >= minTotal)` with `minTotal = 100m`, then sets `minTotal = 300m`, then loops. 1. **Building the query** prints "Query built, nothing parsed yet": no `decimal.Parse` has run. 2. **Reassigning** `minTotal` to 300 updates the closure field the lambda will read. 3. **The `foreach`** starts calling the predicate. Order 1 (250) fails `>= 300` and is skipped, which proves the **new** threshold is in force; with 100 it would have been printed. 4. Order 2 (500) passes and is printed. 5. Order 3 has the text "n/a": `decimal.Parse` throws **`FormatException` inside the `foreach`**, many lines after the `Where` call that mentions `Parse`. 6. A separate call, `Where` on a null source, throws **`ArgumentNullException`** with `ParamName` "source" immediately, with no enumeration at all. ## Exceptions surface where the work happens - A deferred query's lambdas run inside `MoveNext`, so their exceptions are thrown from whatever enumerates the query: a `foreach`, `ToList()`, `Count()`, `First()`. - That can be far from the code that built the query, even in another method or class if the query was returned. Stack traces show the enumerating frame and the lambda, which can mislead a reader looking for the `Where` line. - A `try`/`catch` around query construction catches **nothing** from the predicate. Put it around the enumeration, or around a `ToList()` that forces the work into the protected region. - Each new enumeration re-runs the lambdas, so a row that fails will fail again on every pass. ## What is checked at the call and what waits | Problem | When it surfaces | |---|---| | `null` source or `null` predicate passed to `Where`, `Select`, `OrderBy` | immediately, at the operator call (`ArgumentNullException`) | | An exception thrown by the predicate, selector or key selector | during enumeration, from `MoveNext` | | A captured variable's value | read during enumeration, at each predicate call | | The source list changing during a `foreach` over the query | during enumeration (`InvalidOperationException`) | The first row holds because the `System.Linq` operators validate arguments in the method itself before creating their iterator objects. A hand-written iterator method with `yield return` does not get this for free; making its argument checks eager is a technique covered with yield-based methods. ## Pinning the inputs - **Copy before building.** `var threshold = minTotal;` with `threshold` never reassigned gives the lambda a variable whose value cannot change. A parameter of a small query-building method works the same way. - **Materialise where the inputs are known.** `ToList()` immediately after building the query runs the predicates with the current values and stores the results. - **Validate data before querying** when a bad row should fail early, for example by parsing into a typed record first, or use `decimal.TryParse` in the predicate when bad rows should simply be skipped. - **Watch loops that build queries.** Adding one `Where` per filter inside a `for` loop that uses the loop counter in the lambda makes every lambda share that single counter, which has moved past the end by the time the query runs; copy it to a local inside the loop body. A `foreach` iteration variable is fresh on every iteration since C# 5, so it does not have this problem. ## Summary - A lambda in a LINQ query reads captured locals when it runs, not when the query is built. - Exceptions from query lambdas are thrown by the code that enumerates, not by the operator call. - Argument checks for null sources and delegates happen immediately. - Copy the value to an unchanging local, or materialise at the point the inputs are right.
- Why does Where throw ArgumentNullException at once when its predicate runs only later?The `System.Linq` operators check their arguments in the method body before constructing the iterator object they return, so a null `source` or `predicate` is reported on the call line. Only the work inside the returned iterator is deferred. A hand-written `yield return` method behaves differently, because its whole body, checks included, waits for the first `MoveNext`; splitting the checks out is covered with yield-based methods.
- A for loop adds one Where per limit with q = q.Where(x => x > limits[i]); why does enumeration throw IndexOutOfRangeException?Every lambda captures the same `for` variable `i`. The loop finishes with `i` equal to `limits.Length`, and only then does enumeration run the predicates, so each reads `limits[limits.Length]`. Copy the counter into a local declared inside the loop body, `var limit = limits[i];`, and capture that. A `foreach` iteration variable is a fresh variable per iteration since C# 5, so `foreach (var limit in limits)` is already safe.
- The lambda copies minTotal's value when Where is called
- A try/catch around the query declaration catches errors from the predicate
- Deferred execution also delays ArgumentNullException for a null source
- C# forbids reassigning a local after a lambda captures it
- Calling ToList() is the only way to pin a threshold