I was just browsing and came across this question:
Action vs delegate event
The answer from nobug included this code:
protected virtual void OnLeave(EmployeeEventArgs e) {
var handler = Leave;
if (handler != null)
handler(this, e);
}
Resharper also generates similar code when using the "create raising method" quick-fix.
My question is, why is this line necessary?:
var handler = Leave;
Why is it better than writing this?:
protected virtual void OnLeave(EmployeeEventArgs e) {
if (Leave != null)
Leave(this, e);
}
To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you're handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button.
When testing that a class raises events correctly, there are three elements to verify. Firstly, the class should raise the correct event according to the process being executed. Secondly, the event should refer to the object that raised it.
Use the Shared modifier to create a shared event if you need to raise an event from a constructor. You can change the default behavior of events by defining a custom event. For custom events, the RaiseEvent statement invokes the event's RaiseEvent accessor. For more information on custom events, see Event Statement.
EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.
It's better because there is a tiny possibility that Leave
becomes null after the null check, but before the invocation (which would cause your code to throw a NullReferenceException
). Since the delegate type is immutable, if you first assign it to a variable this possibility goes away; your local copy will not be affected by any changes to Leave
after the assignment.
Note though that this approach also creates a issue in reverse; it means that there is a (tiny, but existing) possibility that an event handler gets invoked after it has been detached from the event. This scenario should of course be handled gracefully as well.
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