Using lambda syntax to create a closure C# with Example



Using lambda syntax to create a closure C# with Example

See remarks for discussion of closures. Suppose we have an interface: 
public interface IMachine 
{ 
TState State { get; } 
public void Input(TInput input); 
} 
and then the following is executed: 
IMachine machine = ...; 
Func 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. 

0 Comment's

Comment Form

Submit Comment