CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
Console.WriteLine("Message from Car: {0}", e.msg);
};
c1.Exploded += delegate(object sender, CarEventArgs e)
{
Console.WriteLine("Fatal Message from Car: {0}", e.msg);
};
// This will eventually trigger the events.
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
}
}
Note The final curly bracket of an anonymous method must be terminated by a semicolon. If you fail to do so,
you are issued a compilation error.
Again, notice that the Program type no longer defines specific static event handlers such as
CarAboutToBlow() or CarExploded(). Rather, the unnamed (a.k.a. anonymous) methods are defined
inline at the time the caller is handling the event using the += syntax. The basic syntax of an anonymous
method matches the following pseudo-code:
class Program
{
static void Main(string[] args)
{
SomeType t = new SomeType();
t.SomeEvent += delegate (optionallySpecifiedDelegateArgs)
{ /* statements */ };
}
}
When handling the first AboutToBlow event within the previous Main() method, notice that you are
not specifying the arguments passed from the delegate:
c1.AboutToBlow += delegate
{
Console.WriteLine("Eek! Going too fast!");
};
Strictly speaking, you are not required to receive the incoming arguments sent by a specific event.
However, if you want to make use of the possible incoming arguments, you will need to specify the
parameters prototyped by the delegate type (as shown in the second handling of the AboutToBlow and
Exploded events). For example:
388