tags:

views:

84

answers:

3

-- If I define an event with an inital empty delegate I don't need to check for null

class MyClass
{
 public event EventHandler<MyEventArgs> MyEvent = delegate { };

 void SomeMethod()
 {
  ...
  MyEvent(); // No need to check for null
  ...
 }
}

-- Otherwise I need to check for null

class MyClass
{
 public event EventHandler<MyEventArgs> MyEvent;

 void SomeMethod()
 {
  ...
  if (MyEvent != null) // No need to check for null
   MyEvent(); 
  ...
 }
}

What's the difference between these? In what cases one is better than another?

Thanks

+1  A: 

At our company we wrote an extension method which hooks onto most events, and checks if it's null before invoking.

We reduced this:

var handler = MyEvent;
if (handler != null)
{
    handler(...);
}

to

MyEvent.SafeTrigger(...);
Andy Shellam
@Andy: check out this thread: http://stackoverflow.com/questions/2282894/event-handler-raising-method-convention
Hans Passant
Yeah inside the SafeTrigger method that's what it does. Because SafeTrigger is an extension method, if MyEvent is null, the extension method gets a null argument.
Andy Shellam
+2  A: 

First one is applicable solution, but it has very very little performance penalty to call extra empty delegate.

Second solution is not thread safe (if it matters for you, of cause).

You should use following:

var handler = MyEvent;
if (handler != null )
  handler(this, new MyEventArgs());
Sergey Teplyakov
+1 for thread safety
Richard Szalay
+3  A: 

The upvoted answer is dramatically wrong, I have to post an answer. Somebody is wrong on the Internet, can't come to bed just yet.

It is convenient but it doesn't come for free. The compiler has to generate a class for the anonymous method and the JIT compiler has to generate code for it. And that code always executes when you raise the event, whether or not a client has subscribed an event handler. The null check code also always executes, but that takes a lot less code and time.

This isn't a lot of code and a lot of time. The null check takes 2 machine code instructions and should execute in a single CPU cycle. The anonymous delegate takes about an order of magnitude more but that's still not a lot on a modern machine. Personally, I'm too old to be wasteful like that, two invariably is my choice.

Not in the least because that's the standard pattern, everybody recognizes it.

Hans Passant