Using lambda syntax to create a closure

suggest change

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 => {
    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.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents