Closures · TL;DR
1 min readTL;DR
A closure is a function bundled with the variables it uses from the scope around it, so it can keep using them after that scope has returned. In C#, any lambda (see the Lambda Expressions module), anonymous method or local function that refers to an outer local variable or parameter is a closure. The compiler makes this work by moving the captured variables off the stack into a compiler-generated heap object (a "display class") and turning the lambda into a method on that object; the delegate then points at that object. Consequences you are expected to know: closures capture variables, not values; they cost heap allocations; they extend the lifetime of everything they capture (a classic leak); and for-loop variables are shared between iterations. static lambdas (C# 9) forbid capturing, and local functions that are not turned into delegates can capture without allocating.