Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising Events in C#: performance and elegance

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:

  1. myHandler is initialized with an empty lambda: myHandler = (sender, e) => { };
  2. myHandler is expected never to be null, so raising would simply become: 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?

like image 801
M.A. Hanin Avatar asked Jan 18 '23 04:01

M.A. Hanin


1 Answers

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.

like image 105
Marc Gravell Avatar answered Jan 29 '23 00:01

Marc Gravell