NullReference when noone listens

I just finished an MVC implementation for WinForms as a tutorial for whomever and as a walkthrough for myself to see if I could find a nice tidy way to organize my ever increasingly Forms classes. I noticed something I just can't figure out.

When publishing an event that noone subscribes to I get a nullreference exception. There are no way (as I can see) to instantiate the Event in and make sure it's not null so I had to go like this:


1:     public event System.EventHandler ButtonPressed;

2:
3: private void btn_Click(object sender, System.EventArgs e)
4: {
5:
6: // if there are no subscribers to the event, it will not have
7: // been instantiated and calling it will cause a
8: // nullreference exception. Don't ask me why.
9: if(ButtonPressed != null)
10: {
11: ButtonPressed(this, new System.EventArgs());
12: }
13: }
14:

 

Is this really the only way to do this? Have I missed out about something with publish/subscribe? It should be possible to scream although noone is actually listening..

1 Comment

  • Yep, that is required... the framework SDK mentions it I believe and their examples show the same;





    protected virtual void OnAlarm(AlarmEventArgs e)


    {


    if (Alarm != null)


    {


    //Invokes the delegates.


    Alarm(this, e);


    }


    }


    }





    VB.NET handles it for you as part of raising an event, so if you are looking at VB code you won't see that check...

Comments have been disabled for this content.