CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
}
}
With the current updates to the Car class, we could stop receiving the engine notification on the
second handler by updating Main() as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Delegates as event enablers *****\n");
// First, make a Car object.
Car c1 = new Car("SlugBug", 100, 10);
c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent));
// This time, hold onto the delegate object,
// so we can unregister later.
Car.CarEngineHandler handler2 = new Car.CarEngineHandler(OnCarEngineEvent2);
c1.RegisterWithCarEngine(handler2);
// Speed up (this will trigger the events).
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
// Unregister from the second handler.
c1.UnRegisterWithCarEngine(handler2);
// We won't see the "uppercase" message anymore!
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
}
Console.ReadLine();
One difference in Main() is that this time we are creating a Car.CarEngineHandler object and storing
it in a local variable so we can use this object to unregister with the notification later on. Thus, the
second time we speed up the Car object, we no longer see the uppercase version of the incoming
message data, as we have removed this target from the delegate’s invocation list.
Source Code The CarDelegate project is located under the Chapter 10 subdirectory.
Method Group Conversion Syntax
In the previous CarDelegate example, we explicitly created instances of the Car.CarEngineHandler
delegate object in order to register and unregister with the engine notifications:
372