Closures

Closures are useful, but dangerous tools. Anonymous methods and lambda expressions are not always closures, but they can be. It all depends on whether the method uses data outside of its own scope and parameter list or not.

For example, the following anonymous function would not be a closure, since it is self-contained and functionally equivalent to any other locally defined function:

System.Func<int,int> anon = (x) => { return x; };

int result = anon(5); // result = 5

However, if the anonymous function pulled in data from outside itself, it becomes a closure, as it closes the environment around the required data. The following would result in a closure:

int i = 1024;
System.Func<int,int> anon = (x) => { return x + i; };
int result = anon(5);

In order to complete this transaction, the compiler must define a new custom class that can reference the environment where the i data value would be accessible. At runtime, it creates the corresponding object on the heap and provides it to the anonymous function. Note that this includes value types (as per the preceding example), which were originally on the stack, possibly defeating the purpose of them being allocated on the stack in the first place. So, we should expect each invocation of the second method to result in heap allocations and inevitable garbage collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.62.103