Setting default event handler

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.
 
J

Jonathan

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
 
S

Sin Jeong-hun

Thanks. Why I didn't come up with that simple if statement.
Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top