Saturday, December 24, 2005 - Posts

Event Handlers aren't as straightforward as they appear

I'm not a c# expert, but I likt to think I can get to the bottom of most stuff. This especially true with the way I think most of .Net is written, its fairly obvious once you think about it. However events are something that has just got me.

So I've created a class with an event on it and then tried to raise the event only to get a null exception !! whats that about. I've used the same code to raise the event, myEvent (this, args).

So I google and as ever find the answer quite quickly. The issue I have is that I was raising the event at a point where there are no handlers attached to the event i.e. the constructor. Therefore when the event was raise there wasn't any where to raise it to so you get the null exception. The way round it is to put some null checking in.

myEventHandler foo = myEvent;
if (foo!=null)
   foo(this, args)

Thanks to Roland for the pointers and the argument that this isn't intuitive. I agree.

http://weblogs.asp.net/rweigelt/archive/2005/01/15/353333.aspx