Back to results for “Delegates”
C# › Delegates, Events & Lambdas

What is a closure and what is a common pitfall?

Intermediate

Answer

A closure is a lambda that captures variables from its enclosing scope. A classic pitfall is capturing a loop variable by reference so all lambdas see its final value.
var fns = new List<Func<int>>();
foreach (var i in Enumerable.Range(0,3)) fns.Add(() => i); // each captures its own i (C# 5+)
Real-world example Building event handlers in a loop that must remember the item they were created for.