
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
540
|
Chapter 9: Delegates, Events, and Anonymous Methods
What does this mean? It means that, inside of the code of the anonymous method,
you can touch variables outside of the scope of that method. There is a concept of
“capturing” the variables that occurs when an anonymous method actually makes
reference to one of the outer variables. In the following example, the
count variable is
captured and incremented by the anonymous method. The
count variable is not part
of the original scope of the anonymous method but part of the outer scope. It is
incremented and then the incremented value is returned and totaled.
delegate int Count( );
int count = 0;
int total = 0;
Count countUp = delegate { return count++; };
for(int i=0;i<10;i++)
{
total += countUp( );
}
Debug.WriteLine("Total = " + total);
What capturing actually does is extend the lifetime of the outer variable to coincide
with the lifetime of the underlying delegate instance that represents the anonymous
method. This should encourage you to be careful about what you touch from inside
an anonymous method. You could be causing things to hang around a lot longer
than you originally planned on. The garbage collector won’t get a chance to clean up
those outer variables until later once they are used in the anonymous method. Cap-
turing outer variables ...