CHAPTER 10 DELEGATES, EVENTS, AND LAMBDA EXPRESSIONS
}
static void CallWhenExploded(string msg)
{ Console.WriteLine(msg); }
}
static void CallHereToo(string msg)
{ Console.WriteLine(msg); }
Exposing public delegate members breaks encapsulation, which not only can lead to code that is
hard to maintain (and debug), but could also open your application to possible security risks! Here is the
output of the current example:
***** Agh! No Encapsulation! *****
Sorry, this car is dead...
Sorry, this car is dead...
hee, hee, hee...
Obviously, you would not want to give other applications the power to change what a delegate is
pointing to or to invoke the members without your permission. Given this, it is common practice to
declare private delegate member variables.
Source Code The PublicDelegateProblem project is located under the Chapter 10 subdirectory.
The C# event Keyword
As a shortcut, so you don’t have to build custom methods to add or remove methods to a delegate’s
invocation list, C# provides the event keyword. When the compiler processes the event keyword, you are
automatically provided with registration and unregistration methods, as well as any necessary member
variables for your delegate types. These delegate member variables are always declared private and,
therefore, they are not directly exposed from the object firing the event. To be sure, the event keyword
can be used to simplify how a custom class sends out notifications to external objects.
Defining an event is a two-step process. First, y ou need to define a delegate type that will hold the
list of methods to be called when the event is fired. Next, you declare an event (using the C# event
keyword) in terms of the related delegate type.
To illustrate the event keyword, create a new Console Application named CarEvents. In this iteration
of the Car class, we will define two events named AboutToBlow and Exploded. These events are associated
to a single delegate type named CarEngineHandler. Here are the initial updates to the Car class:
public class Car
{
// This delegate works in conjunction with the
// Car's events.
public delegate void CarEngineHandler(string msg);
379