Those who prefer reading this site through RSS now can also subscribe for updates to .NET Tips & Tricks Community.
Be aware that if there are no subscribers a .NET event will be null. Therefore when raising the event from C# test it for null first.
public event EventHandler SelectedNodeChanged;
protected virtual void OnSelectedNodeChanged(object sender, EventArgs e)
{
//Event will be null if there are no subscribers
if (SelectedNodeChanged != null)
SelectedNodeChanged(this, e);
}
However in multithreaded application the last subscriber can unsubscribe immediately after the null check and before the event is raised. To avoid a null reference exception make a temporary copy of the event.
//Make a temporary copy of the event to avoid possibility of
//a race condition if the last subscriber unsubscribes
//immediately after the null check and before the event is raised.
EventHandler handler = SelectedNodeChanged;
if (handler != null)
handler(this, e);
submitted by Sergey P.