2
class Plane 
{
    public event EventHandler Land;

    protected void OnLand()
    {
        if ( null != Land ) 
        {
            Land( this, null );
        }
    }
}

it is event handler best practice to do instead:

EventHandler temp = Land;
if ( null != temp ) 
{
    temp( this, null );
}

Is that truly necessary? In what case could temp be different from Land?

lance
  • 16,092
  • 19
  • 77
  • 136
Pyadav
  • 135
  • 7
  • I do not see where you subscribe to the event. You might also want to check to see if an Invoke is required if you are going to be trying to update the user interface. – Security Hound Oct 12 '11 at 18:54

3 Answers3

6

In the case of multi-threaded access, I believe. If you don't cache the reference, another thread can null it out after your guard but before you fire.

Erik Dietrich
  • 6,080
  • 6
  • 26
  • 37
  • I'm pretty sure that since EventHandler is a reference type, if Land were null'd after the nullity check but before the invocation it would still throw a NullReferenceException – Sam Axe Oct 12 '11 at 18:55
  • That's my point. You cache the reference with "temp" as a best practice so that doesn't happen and you don't throw the exception. Temp continues to point to an object in memory for the scope of the method, so invoking temp does not throw an exception. – Erik Dietrich Oct 12 '11 at 19:00
  • Sorry. That is not the manner in which I am used to references operating. But a quick scratch program revealed my mistake. – Sam Axe Oct 12 '11 at 19:10
  • Unfortunately I can not reverse my vote unless you edit your answer. – Sam Axe Oct 12 '11 at 19:10
  • I added a space, if you want to change your vote. If it can't be done, no worries. :) – Erik Dietrich Oct 12 '11 at 19:14
  • 1
    +1 There is another subtle difference: events are immutable, like strings. So `event Action MyEvent; MyEvent += () => Console.WriteLine("Hello 1"); var temp = MyEvent; MyEvent += () => Console.WriteLine("Hello 2"); temp();` will print only `Hello 1`, because temp has an "older" copy of MyEvent. – xanatos Oct 12 '11 at 20:02
2

If you have concurrency with many threads modifying Land.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
1

When in between the test and the raise the last handler is removed from the list by an other thread.

the invokation list of the event will be copied when it changes and the temp reference will still hold the original list.

See: C# Events and Thread Safety

Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115