CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
// This car can send these events.
public event CarEngineHandler Exploded;
public event CarEngineHandler AboutToBlow;
...
}
Sending an event to the caller is as simple as specifying the event by name, along with any required
parameters as defined by the associated delegate. To ensure that the caller has indeed registered with
the event, you will want to check the event against a null value before invoking the delegate’s method
set. With these points in mind, here is the new iteration of the Car’s Accelerate() method:
public void Accelerate(int delta)
{
// If the car is dead, fire Exploded event.
if (carIsDead)
{
if (Exploded != null)
Exploded("Sorry, this car is dead...");
}
else
{
CurrentSpeed += delta;
// Almost dead?
if (10 == MaxSpeed - CurrentSpeed
&& AboutToBlow != null)
{
AboutToBlow("Careful buddy! Gonna blow!");
}
// Still OK!
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
}
}
With this, you have configured the car to send two custom events without having to define custom
registration functions or declare delegate member variables. You will see the usage of this new
automobile in just a moment, but first, let’s check the event architecture in a bit more detail.
Events Under the Hood
When the compiler processes the C# event keyword, it generates two hidden methods, one having an
add_ prefix, the other having a remove_ prefix. Each prefix is followed by the name of the C# event. For
example, the Exploded event results in two hidden methods named add_Exploded() and
remove_Exploded(). If you were to check out the CIL instructions behind add_AboutToBlow(), you would
find a call to the Delegate.Combine() method. Consider the partial CIL code:
380