Friday, December 14, 2007

NullReferenceException raising an event in C#

I was working with events in C# and ran into this exception. System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." This exception was at the exact point in my code where I attempted to raise the event. It turns out that if there are not event handlers attached to your event, an attempt to raise it will give you this exception. To solve it, you have to check to see if its null before raising it.


public class TestEvent{
public event EventHandler MyEvent;
public void RaiseMyEvent(){
if(MyEvent != null){
MyEvent(this, null);
}
}
}


All the samples I was looking at did not check for a null value, so neither did I. Now that I had the problem, I see why I need to check.

9 comments:

  1. Thanks, Kevin - that saved me a considerable amount of troubleshooting time!

    ReplyDelete
  2. Anonymous4:00 PM

    THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU THANK YOU. this was driving me nuts. i knew the problem, but couldnt figure out how to check to see if the event was being handled by the calling class. THANK YOU.

    ReplyDelete
  3. First of all: THANK YOU.. i have went through my code a million times to see where i went wrong...

    Second of all: This is the most STUPID thing i have ever seen on .NET.. when no listeners are registered, it throws an error.. WTF ?

    ReplyDelete
  4. Anonymous5:11 PM

    Ditto,

    100 thanks for posting this.

    Its plain right dumb on the .NET part to give no clue whatsoever.

    If you were closeby, I would pay for your lunch

    Thanks

    ReplyDelete
  5. Anonymous6:23 AM

    Just wanted to say thank you. Saved me hours! Interesting why it would throw an exception. I do remember reading somewhere that the class raising the event doesn't care about the subscribers, turns out not to be the case!

    Cheers,
    Michael.

    ReplyDelete
  6. Anonymous11:20 PM

    for (int i = 0; i < Slength; i++)
    {
    SmyLabels[i].Text = SdataArray[i].ToString();
    SmyLabels[i].BackColor = Color.White;
    }

    how to solve this .. same error

    ReplyDelete
  7. Anonymous4:50 AM

    No other comment just Thank you

    ReplyDelete
  8. Anonymous12:38 AM

    Thanks

    ReplyDelete
  9. Anonymous8:53 AM

    Especially hard to find this when it is a service throwing the error! Thanks for posting this.

    ReplyDelete