
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
544
|
Chapter 9: Delegates, Events, and Anonymous Methods
// Make a newspaper class.
OldNewsPaper DailyPaperFlash = new OldNewsPaper( );
// Hook up the news event to our handler (BreakingNews).
DailyPaperFlash.NewsEvent +=
new EventHandler<OldNewsEventArgs>(BreakingNews);
// Send news.
DailyPaperFlash.TransmitNews("Patriots win again!");
DailyPaperFlash.TransmitNews("4 more years for W.");
DailyPaperFlash.TransmitNews("VS2005 & .NET 2.0 Rocks LA");
}
private static void BreakingNews(object src, NewsEventArgs nea)
{
System.Diagnostics.Debug.WriteLine(nea.LatestNews);
}
}
Discussion
The main benefit of using the generic EventHandler instead of System.EventHandler is
that you write less code. Being able to declare a generic delegate allows you to have
one delegate definition for multiple types. Why is this interesting, you might ask?
Previously, when a delegate or event was declared by a class that wanted to publish
information and allow multiple client classes to subscribe to it, if any data were to be
passed along to the client classes, the convention was that a new class that derived
from
System.EventArgs had to be created. Then the class would be instantiated, filled
with the data, and passed to the client. If the publishing class had only one event to
notify people of, this wasn’t ...