Information Technology Reference
In-Depth Information
are built on delegates to provide type-safe function signatures for event
handlers. Add to this the fact that most examples that use delegates are
events, and developers start thinking that events and delegates are the same
things. In Item 24, I showed you examples of when you can use delegates
without defining events. You should raise events when your type must
communicate with multiple clients to inform them of actions in the sys-
tem. Events are how objects notify observers.
Consider a simple example. You're building a log class that acts as a dis-
patcher of all messages in an application. It will accept all messages from
sources in your application and will dispatch those messages to any inter-
ested listeners. These listeners might be attached to the console, a data-
base, the system log, or some other mechanism. You define the class as
follows, to raise one event whenever a message arrives:
public class
LoggerEventArgs
:
EventArgs
{
public string
Message {
get
;
private set
; }
public int
Priority {
get
;
private set
; }
public
LoggerEventArgs(
int
p,
string
m)
{
Priority = p;
Message = m;
}
}
public class
Logger
{
static
Logger()
{
theOnly =
new
Logger
();
}
private
Logger()
{
}
private static
Logger
theOnly =
null
;
public static
Logger
Singleton
{