6

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);
}
Community
  • 1
  • 1
Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220

3 Answers3

12

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.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
5

In a multi-threaded application, you could get a null reference exception if the caller unregisters from the event. The assignment to a local variable protects against this.

Odds are you'd never see this (until it hurts you the worst). Here's a way of looking at it that shows the problem...

protected virtual void OnLeave(EmployeeEventArgs e) {
  if (Leave != null) //subscriber is registered to the event
  {
    //Subscriber unregisters from event....
    Leave(this, e); //NullReferenceException!
  }
}
Aaron Daniels
  • 9,563
  • 6
  • 45
  • 58
1

Here's an excellent explanation by Eric Lippert :

Events and races

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758