Is it possible to always add an empty event handler?

Possible duplicate:
Is there a drawback in adding an anonymous empty delegate to the event declaration?

The following pattern is quite common when using event handlers (in C #):

public event Action handler; … // some method: if(handler != null) handler(); 

Are there any flaws in appointing an empty delegate for this event? This would save the if !=null condition wherever the event occurs. Of course, this applies only when we cannot guarantee that the appropriate delegate is always assigned to the event.

 public event Action handler; … // in constructor: handler += ()=>{}; … // some method: handler(); 

Of course, there is a slight performance hit, but it makes the code much cleaner. What is the best practice in this case? Any technical flaws?

+6
source share
3 answers

Instead of adding an empty delegate to the constructor, you can transfer the handler to a function that first checks if the handler is null and then calls it. The disadvantage of this is that if you have many events, you will have many functions that wrap each event.

 private void HandlerWrapper() { Action localHandler = handler; if (localHandler != null) handler(); } 
+1
source

An interesting idea, I never thought about it. The way I do my own events is to make OnCustomEventName, taking the parameters for the event, and just check there for null. and call OnCustomEventName from the code wherever I want the event to be raised. Avoids any performance gains and keeps the opcode cleaner than 2-line if you check every time you want the event to fire.

Considering that this does not answer the question about technical flaws, but is more suitable for competitions.

code sample for threadsafe "On" function.

 private void OnCustomEventName() { DelegateName localhandler = CustomEventName; if (localhandler != null) localhandler(); } 
+1
source

In fact, I did not find any big flaws, and usually prefer to check for null. The only problem I don’t think about is that it can lead to annoying actions in the code during debugging (i.e., you need to step over the empty delegate every time you enter the event).

I think that performance is not a problem - if application performance degenerates significantly by triggering events, the event probably should not have been there first.

0
source

Source: https://habr.com/ru/post/916552/


All Articles