Information Technology Reference
In-Depth Information
Extension of Captured Variable's Lifetime
A captured outer variable remains alive, as long as its capturing method is part of the delegate,
even if the variable would have normally gone out of scope.
For example, the code in Figure 15-14 illustrates the extension of a captured variable's
lifetime.
Local variable
x
is declared and initialized inside a block.
Delegate
mDel
is then instantiated, using an anonymous method that captures outer
variable
x
.
When the block is closed,
x
goes out of scope.
f the
WriteLine
statement following the close of the block were to be uncommented, it
would cause a compile error, because it references
x
, which is now out of scope.
The anonymous method inside delegate
mDel
, however, maintains
x
in its environment
and prints its value, when
mDel
is invoked.
Figure 15-14.
Variable captured in an anonymous method
This code produces the following output:
Value of x: 5