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:

Richard K. said...

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

Anonymous said...

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.

Noctris said...

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 ?

Anonymous said...

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

Anonymous said...

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.

Anonymous said...

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

how to solve this .. same error

Anonymous said...

No other comment just Thank you

Anonymous said...

Thanks

Anonymous said...

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