Reputation: 273643
Let's say that I am writing a class library of some sort. I have a class:
public class PopupControl : UserControl {
// Some code
public event EventHandler PopupFinished;
}
If I want to handle this event in another class, I just use the +=
operator and nothing special happens. However, when the event is not handled anywhere, PopupFinished
is null
. And when I call PopupFinished (this, EventArgs.Empty)
, I get a NullReferenceException
. So I need to do this:
public PopupControl () {
PopupFinished += popupFinished;
//Some more code
}
private void popupFinished (object sender, EventArgs e) {}
This doesn't sound like a good programming practice though. (or is it?)
Then I thought of another way:
try {
PopupFinished (this, EventArgs.Empty);
} catch (NullReferenceException) {}
But that doesn't sound right either.
Please tell me which of the above is better and whether there is another way to do that. Thanks!
Upvotes: 2
Views: 70
Reputation: 1852
Do a test to check PopupFinished
is not null before calling it.
if(PopupFinished != null)
PopupFinished();
Upvotes: 3