Information Technology Reference
In-Depth Information
Scope of Variables and Parameters
The scopes of parameters and local variables declared in an anonymous method are limited to
the body of the implementation code, as illustrated in Figure 15-12.
For example, the following anonymous method defines parameter y and local variable z .
After the close of the body of the anonymous method, y and z are no longer in scope. The last
line of the code would produce a compile error.
Figure 15-12. Scope of variables and parameters
Outer Variables
Unlike the named methods of a delegate, anonymous methods have access to the local vari-
ables and environment of the scope surrounding them.
￿
Variables from the surrounding scope are called outer variables .
￿
An outer variable used in the implementation code of an anonymous method is said to
be captured by the method.
For example, the code in Figure 15-13 shows variable x defined outside the anonymous
method. The code in the method, however, has access to x and can print its value.
Figure 15-13. Using an outer variable
Search WWH ::




Custom Search