Sign in to track progress and bookmarks.
LINQ expressions often use Closures to capture external variables. If not understood, this can lead to memory leaks and subtle bugs that are hard to track down.
When you reference a variable outside your lambda, C# creates a hidden 'Closure' class to hold that variable. If your LINQ query has a long lifetime (e.g., stored in a static variable), the captured object will NEVER be garbage collected.
var hugeObject = new LargeData();
// hugeObject is now 'captured' and cannot be GC-ed
// as long as 'query' exists.
var query = list.Where(x => x.Source == hugeObject);
Because variables are captured by Reference, if you change the variable value AFTER defining the query but BEFORE executing it, you will get unexpected results. **Architect Tip:** Always copy your loop variable to a local 'snapshot' variable before using it in a LINQ expression inside a loop (though modern C# has improved this for foreach).
Q: "How do I fix memory leaks in long-running LINQ queries?"
Architect Answer: "Nullify your references when they are no longer needed, or use **Static Anonymous Functions** (C# 9+) to ensure you don't accidentally capture external state. By marking a lambda as static: list.Select(static x => x.Name), the compiler will throw an error if you try to reference any outside variable, preventing accidental leaks."
Quizzes linked to this course—pass to earn certificates.
On this page
1. Capturing Variables 2. Access to Modified Closures 3. Architect Insight