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

Feedback about page:

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


Lambda Expressions:
* Using lambda syntax to create a closure

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
82 Lambda Expressions
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script