CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
c1.AboutToBlow += delegate(object sender, CarEventArgs e)
{
Console.WriteLine("Critical Message from Car: {0}", e.msg);
};
Accessing Local Variables
Anonymous methods are interesting in that they are able to access the local variables of the method that
defines them. Formally speaking, such variables are termed outer variables of the anonymous method. A
few important points about the interaction between an anonymous method scope and the scope of the
defining method should be mentioned:
•
An anonymous method cannot access ref or out parameters of the defining
method.
•
An anonymous method cannot have a local variable with the same name as a local
variable in the outer method.
•
An anonymous method can access instance variables (or static variables, as
appropriate) in the outer class scope.
•
An anonymous method can declare local variables with the same name as outer
class member variables (the local variables have a distinct scope and hide the
outer class member variables).
Assume our Main() method defined a local integer named aboutToBlowCounter. Within the
anonymous metho ds that handle the AboutToBlow event, we will increment this counter by one and print
out the tally before Main() completes:
static void Main(string[] args)
{
Console.WriteLine("***** Anonymous Methods *****\n");
int aboutToBlowCounter = 0;
// Make a car as usual.
Car c1 = new Car("SlugBug", 100, 10);
// Register event handlers as anonymous methods.
c1.AboutToBlow += delegate
{
aboutToBlowCounter++;
Console.WriteLine("Eek! Going too fast!");
};
c1.AboutToBlow += delegate(object sender, CarEventArgs e)
{
aboutToBlowCounter++;
Console.WriteLine("Critical Message from Car: {0}", e.msg);
};
...
389