CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
***** Delegates as event enablers *****
***** Speeding
CurrentSpeed =
CurrentSpeed =
CurrentSpeed =
up *****
30
50
70
***** Message From Car Object *****
=> Careful buddy! Gonna blow!
***********************************
CurrentSpeed = 90
***** Message From Car Object *****
=> Sorry, this car is dead...
***********************************
Enabling Multicasting
Recall that .NET delegates have the built-in ability to multicast. In other words, a delegate object can
maintain a list of methods to call, rather than just a single method. When you want to add multiple
methods to a delegate object, you simply make use of the overloaded += operator, rather than a direct
assignment. To enable multicasting on the Car class, we could update the
RegisterWithCarEngine()method, like so:
public class Car
{
// Now with multicasting support!
// Note we are now using the += operator, not
// the assignment operator (=).
public void RegisterWithCarEngine(CarEngineHandler methodToCall)
{
listOfHandlers += methodToCall;
}
...
}
When you use the += operator on a delegate object, the compiler resolves this to a call on the static
Delegate.Combine() method. In fact, you could call Delegate.Combine() directly; however, the +=
operator offers a simpler alternative. There is no need to modify your current RegisterWithCarEngine()
method, but here is an example if using Delegate.Combine() rather than the += operator:
public void RegisterWithCarEngine( CarEngineHandler methodToCall )
{
if (listOfHandlers == null)
listOfHandlers = methodToCall;
else
Delegate.Combine(listOfHandlers, methodToCall);
}
370