CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
Source Code The GenericPrimAndProperCarEvents project is located under the Chapter 10 subdirectory.
Understanding C# Anonymous Methods
As you have seen, when a caller wants to listen to incoming events, it must define a custom method in a
class (or structure) that matches the signature of the associated delegate. For example:
class Program
{
static void Main(string[] args)
{
SomeType t = new SomeType();
}
}
// Assume "SomeDelegate" can point to methods taking no
// args and returning void.
t.SomeEvent += new SomeDelegate(MyEventHandler);
// Typically only called by the SomeDelegate object.
public static void MyEventHandler()
{
// Do something when event is fired.
}
When you think about it, however, methods such as MyEventHandler() are seldom intended to be
called by any part of the program other than the invoking delegate. As far as productivity is concerned, it
is a bit of a bother (though in no way a show-stopper) to manually define a separate method to be called
by the delegate object.
To address this point, it is possible to associate an event directly to a block of code statements at the
time of event registration. Formally, such code is termed an anonymous method. To illustrate the syntax,
check out the following Main() method, which handles the events sent from the Car class using
anonymous methods, rather than specifically named event handlers:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Anonymous Methods *****\n");
Car c1 = new Car("SlugBug", 100, 10);
// Register event handlers as anonymous methods.
c1.AboutToBlow += delegate
{
Console.WriteLine("Eek! Going too fast!");
};
c1.AboutToBlow += delegate(object sender, CarEventArgs e)
{
387