I came across this question in a Microsoft Practice Test and I got confused. Here is the question:
Which of the following C# code samples is the proper way to raise an event, assuming that the Alarm event, the AlarmEventArgs class, and the AlarmEventHandler delegate have been declared?
Here is the "correct" answer they provided:
AlarmEventArgs e = new AlarmEventArgs(1, 2);
AlarmEventHandler handler = Alarm;
if (handler != null)
{
handler(this, e);
}
However, there is also another answer which seems correct.
AlarmEventArgs e = new AlarmEventArgs(1, 2);
if (Alarm!= null)
{
Alarm (this, e);
}
I personally, always use the second method. It works just fine. Can someone please tell me why I should use the first method instead of second?
Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method On EventName; for example, OnDataReceived .
Events in C# are simple things on the face of it. You create an event signature using a delegate type and mark it with the event keyword. External code can register to receive events. When specific things occur within your class, you can easily trigger the event, notifying all external listeners.
The EventArgs class is the base class for all the event data classes. . NET includes many built-in event data classes such as SerialDataReceivedEventArgs. It follows a naming pattern of ending all event data classes with EventArgs. You can create your custom class for event data by deriving EventArgs class.
In a multi-threaded environment, it's possible that the event handler may be updated while your event is being dispatched. To avoid this scenario, you assign the handler to a local variable before checking for null and dispatching the message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With