Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handler raising method convention

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);
}
like image 850
Neil Barnwell Avatar asked Feb 17 '10 17:02

Neil Barnwell


People also ask

What are event handler methods?

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.

Which of the following is correct for testing if event is raised?

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.

How do you use RaiseEvent?

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.

What is EventArgs E in C#?

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.


1 Answers

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.

like image 73
Fredrik Mörk Avatar answered Sep 21 '22 12:09

Fredrik Mörk