Free mag vol1 | Page 430

CHAPTER 10  DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS } } } if (CurrentSpeed >= MaxSpeed) carIsDead = true; else Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed); Notice that before we invoke the methods maintained by the listOfHandlers member variable, we are checking it against a null value. The reason is that it will be the job of the caller to allocate these objects by calling the RegisterWithCarEngine() helper method. If the caller does not call this method and we attempt to invoke the delegate’s invocation list, we will trigger a NullReferenceException at runtime. Now that we have the delegate infrastructure in place, observe the updates to the Program class: 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); // Now, tell the car which method to call // when it wants to send us messages. c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent)); // Speed up (this will trigger the events). Console.WriteLine("***** Speeding up *****"); for (int i = 0; i < 6; i++) c1.Accelerate(20); Console.ReadLine(); } // This is the target for incoming events. public static void OnCarEngineEvent(string msg) { Console.WriteLine("\n***** Message From Car Object *****"); Console.WriteLine("=> {0}", msg); Console.WriteLine("***********************************\n"); } } The Main() method begins by simply making a new Car object. Since we are interested in hearing about the engine events, our next step is to call our custom registration function, RegisterWithCarEngine(). Recall that this method expects to be passed an instance of the nested CarEngineHandler delegate, and as with any delegate, we specify a “method to point to” as a constructor parameter. The trick in this example is that the method in question is located back in the Program class! Again, notice that the OnCarEngineEvent() method is a dead-on match to the related delegate in that it takes a string as input and returns void. Consider the output of the current example: 369