Lambda Expressions

suggest change

Remarks

Closures

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);

safeApplyFiltererPredicate captures the variables filterer and i, not a copy of the object filterer referred to when the lambda was created. Later assignments to those variables are visible to the lambda, and the lambda keeps them reachable. Its Invoke method behaves like

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

This matters for garbage collection. Reassigning filterer changes what the lambda calls. Mutating the object it currently refers to is also visible inside the lambda.

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

E.g.

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:

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



Table Of Contents