Sobes.tech
Middle+

When does closure occur?

sobes.tech AI

Answer from AI

In C#, a closure occurs when a lambda expression or anonymous method captures variables from the outer scope, and these variables are preserved and accessible even after exiting the scope in which they were declared.

For example:

Func<int> CreateCounter()
{
    int count = 0;
    return () => ++count;
}

var counter = CreateCounter();
Console.WriteLine(counter()); // 1
Console.WriteLine(counter()); // 2

Here, the lambda captures the variable count, and it maintains its state between calls. The closure occurs at the moment the lambda is created, when it "captures" the external variables.