C# Language Lambda Expressions Using lambda syntax to create a closure

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

See remarks for discussion of closures. Suppose we have an interface:

public interface IMachine<TState, TInput>
{
    TState State { get; }
    public void Input(TInput input);
}

and then the following is executed:

IMachine<int, int> machine = ...;
Func<int, int> machineClosure = i => {
    machine.Input(i);
    return machine.State;
};

Now machineClosure refers to a function from int to int, which behind the scenes uses the IMachine instance which machine refers to in order to carry out the computation. Even if the reference machine goes out of scope, as long as the machineClosure object is maintained, the original IMachine instance will be retained as part of a 'closure', automatically defined by the compiler.

Warning: this can mean that the same function call returns different values at different times (e.g. In this example if the machine keeps a sum of its inputs). In lots of cases, this may be unexpected and is to be avoided for any code in a functional style - accidental and unexpected closures can be a source of bugs.



Got any C# Language Question?