Lambda Expressions

suggest change



Lambda expressions will implicitly capture variables used and create a closure. A closure is a function along with some state context. The compiler will generate a closure whenever a lambda expression ‘encloses’ a value from its surrounding context.

E.g. when the following is executed

Func<object, bool> safeApplyFiltererPredicate = o => (o != null) && filterer.Predicate(i);

safeApplyFilterPredicate refers to a newly created object which has a private reference to the current value of filterer, and whose Invoke method behaves like

o => (o != null) && filterer.Predicate(i);

This can be important, because as long as the reference to the value now in safeApplyFilterPredicate is maintained, there will be a reference to the object which filterer currently refers to. This has an effect on garbage collection, and may cause unexpected behaviour if the object which filterer currently refers to is mutated.

On the other hand, closures can be used to deliberate effect to encapsulate a behaviour which involves references to other objects.


var logger = new Logger();
Func<int, int> Add1AndLog = i => {
    logger.Log("adding 1 to " + i);
    return (i + 1);

Closures can also be used to model state machines:

Func<int, int> MyAddingMachine() {
    var i = 0;
    return x => i += x;

Feedback about page:

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

Table Of Contents