O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Closures: Captured Outer Variables

Because of their capability to capture local variables from the outer scope, anonymous function expressions are much more powerful than would seem to be the case at first glance. Let’s take a look at an example:

static void Main() {    int factor = 2;    BinOp addAndFactor = delegate (int a, int b) { return factor * (a + b); };    int six = addAndFactor(1, 2);}

In the preceding code fragment, the local variable factor is captured inside the embedded inline method declaration. This is a powerful capability that reduces plumbing significantly. Imagine how you would communicate the factor value to a delegate if you couldn’t simply use an anonymous function expression. A more real-world ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required