
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
542
|
Chapter 9: Delegates, Events, and Anonymous Methods
This code sets up an event that will report the news to subscribers as it comes in. It
passes them the news data as an argument of type
OldNewsEventArgs that has a
LatestNews property.
As you can see from this example, whenever you had to set up multiple event han-
dlers, it became an exercise in copy-and-paste and changing the event argument class
type over and over again. It would be nice to not have to define lots of delegates and
events just to change the event arguments, as all events (and corresponding han-
dlers) are supposed to look like this:
void [EventHandler](object sender, [EventArgs] args)
{
// Do something about this event firing.
}
Solution
EventHandler<T> takes a type parameter that represents the type of the System.
EventArgs
derived class to use in your event handlers. The beauty of this is that you
no longer have to keep creating a delegate and an event for every event you wish to
publish from your class. Even better, the Framework has to have only one event dele-
gate instead of one for every event that passes custom data! Using the example
shown in the Problem section, you can now rewrite the declaration of the event han-
dler like this:
// Old way
public delegate void NewsEventHandler(Object sender, OldNewsEventArgs ...