I have seen a few mentions of this idiom (including on SO):
// Deliberately empty subscriber public event EventHandler AskQuestion = delegate {};
The upside is clear - it avoids the need to check for null before raising the event.
However, I am keen to understand if there are any downsides. For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?
Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.
Anonymous methods are a simplified way for you to assign handlers to events. They take less effort than delegates and are closer to the event they are associated with. You have the choice of either declaring the anonymous method with no parameters or you can declare the parameters if you need them.
Yes, Events! This is a simplified explanation on why we use events even though we can already use delegates: To provide encapsulation and not exposing business logic. To prevent Team Client from clearing all assign methods to delegates (You cannot do that for events):
An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events.
Instead of inducing performance overhead, why not use an extension method to alleviate both problems:
public static void Raise(this EventHandler handler, object sender, EventArgs e) { if(handler != null) { handler(sender, e); } }
Once defined, you never have to do another null event check again:
// Works, even for null events. MyButtonClick.Raise(this, EventArgs.Empty);
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