Sobes.tech
Junior — Middle

Explain the concept of closure in programming and how it is used

sobes.tech AI

Answer from AI

A closure is a function that captures and remembers variables from its surrounding context, even after that context has ceased to exist. In C#, closures often occur when using lambda expressions or anonymous methods that access variables from an outer method.

Example:

Func<int> CreateCounter()
{
    int count = 0;
    return () => ++count; // lambda captures the variable count
}

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

Here, the lambda function retains access to the variable count even after the CreateCounter method has finished. This allows maintaining state between calls.

Using closures is useful for creating functions with internal state, handling events, deferred execution, and other scenarios where maintaining context is necessary.

Explain the concept of closure in programming and how… - sobes.tech