CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
In any case, the caller can now register multiple targets for the same callback notification. Here, our
second handler prints the incoming message in uppercase, just for display purposes:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Delegates as event enablers *****\n");
// First, make a Car object.
Car c1 = new Car("SlugBug", 100, 10);
// Register multiple ta rgets for the notifications.
c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent));
c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent2));
}
// Speed up (this will trigger the events).
Console.WriteLine("***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
// We now have TWO methods that will be called by the Car
// when sending notifications.
public static void OnCarEngineEvent(string msg)
{
Console.WriteLine("\n***** Message From Car Object *****");
Console.WriteLine("=> {0}", msg);
Console.WriteLine("***********************************\n");
}
}
public static void OnCarEngineEvent2(string msg)
{
Console.WriteLine("=> {0}", msg.ToUpper());
}
Removing Targets from a Delegate’s Invocation List
The Delegate class also defines a static Remove() method that allows a caller to dynamically remove a
method from a delegate object’s invocation list. This makes it simple to allow the caller to “unsubscribe”
from a given notification at runtime. While you could call Delegate.Remove() directly in code, C#
developers can use the -= operator as a convenient shorthand notation. Let’s add a new method to the
Car class that allows a caller to remove a method from the invocation list:
public class Car
{
...
public void UnRegisterWithCarEngine(CarEngineHandler methodToCall)
{
listOfHandlers -= methodToCall;
371