Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary have someone registered to an event before you can raise it?

Tags:

c#

events

It sounds crazy but I created an event in the class and tried to raise it without having anyone registering to it. However it would give an exception. Is it necessary to have someone register to it before raising the exception? If so then what are the work arounds?

like image 238
Umair Ahmed Avatar asked Nov 29 '22 05:11

Umair Ahmed


2 Answers

yes, an event with no-one registered on it is null. The standard way of firing events is:

event EventHandler MyEvent;

private void FireMyEvent(EventArgs e) {
    var handler = MyEvent;
    if (handler != null)
        handler(this, e);
}

Eric Lippert has written a fantastic article on why this pattern is the 'correct' way of firing events

like image 112
thecoop Avatar answered Dec 04 '22 23:12

thecoop


Yes. If there are no subscribers, the event will be null and you will get a NullReferenceException when you call it. The correct way of doing the check is as thecoop has said, but there is a simple "shortcut":

public event EventHandler Event = delegate {};

This causes the event to have a default subscriber that does nothing, and so will not throw an exception if there are subscribers. There is a slight performance overhead of doing this, but it does remove the need to check for nulls.

like image 43
adrianbanks Avatar answered Dec 05 '22 01:12

adrianbanks