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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With