Raising anEvent
An event can be raised, just like a delegate, by calling it like a method. When you raise
an event, all the attached delegates are called in sequence. For example, here's the
TemperatureMonitor class with a private Notify method that raises the
MachineryOverheating event:
class TemperatureMonitor
{
public delegate void StopMachinerDelegate;
public event StopMachineryDelegate MachineOverheating;
private void Notify()
{
if (this.MachineOverheating != null)
{
this.MachineOverheating();
}
}
}
This is a common idiom. The null check is necessary because anevent field is implicitly
null and only becomes non-null when a method subscribes to it by using the += operator.
If you try and raise a null event, you will get a NullReferenceException. If the delegate
defining the event expects any parameters, the appropriate arguments must be provided
when you raise the event. You will see some examples of this later.
IMPORTANT
Events have a very useful built-in security feature. A public event (such as
MachineOverheating) can only be raised by methods within the class that define it (the
TemperatureMonitor class). Any attempt to raise the method outside of the class will
result in a compiler error.
.
Raising an Event
An event can be raised, just like a delegate, by calling it like a method. When you raise
an event, all the attached. because an event field is implicitly
null and only becomes non-null when a method subscribes to it by using the += operator.
If you try and raise a null event,