Setting default event handler

  • Thread starter Thread starter Sin Jeong-hun
  • Start date Start date
S

Sin Jeong-hun

Suppose that there is a class I've created, named MyClass.
I defined an event MyEvent by
public event EventHandler MyEvent;

then I fire the event somewhere in the class like this
this.MyEvent(sender,args); <----(1)

It works fine as long as the event is consumed like this
MyClass aClass = new MyClass();
aClass.MyEvent+=new EventHandler(....); <---(2)

But if (2) is omitted, (because the caller doesn't need to consume
the event) then a NullReferenceExepction occurs at (1).

I think I can avoid this by adding an EventHandler in MyClass like
this.MyEvent+=new EventHanlder(...);
but is this the normal way? It looks like a waste because I also
have to create a method that doesn't do anything. Is there any more
efficient way to avoid this?
Thank you.
 
If you copy the delegate instance into a local variable (to prevent
race conditions) and then check that local variable's equality with
null before firing the event, you'll avoid the situation where a
NullReferenceException is thrown.

EventHandler eh = MyEvent;
if (eh != null)
{
eh(sender, args);
}

Cheers,

Jono
 
Back
Top