Being accustomed to VB.NET, I'm used to "just raise events". Sure, custom events differ, but with "regular" events - I don't need to check if the delegate is Nothing
before raising.
With C#, I find myself repeating this pattern:
if (myHandler != null)
{
myHandler(this, new EventArgs());
}
I was thinking that the following pattern might prove more elegant:
myHandler = (sender, e) => { };
myHandler(this, new EventArgs());
Would this pattern be more or less performant than the previous one? Are there other significant considerations I should take into account?
It is something extra to happen in construction, but it won't be huge overhead. One thing to watch is that some serialization frameworks like DataContractSerializer
(WCF) don't run constructors or field initializers, so it may not be non-null after all. Personally, if the majority of your events are EventHandler
, I might be tempted to use an extension method:
public static void SafeInvoke(this EventHandler handler, object sender) {
if (handler != null) handler(sender, EventArgs.Empty);
}
then:
SomeEvent.SafeInvoke(this);
although be frank, I rarely have a problem with simply using the null-check ;p
Another downside is that if you have enough events that this is an issue, you should probably be using EventHandlerList
instead - and this approach won't work with EventHandlerList
.
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