Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to always add an empty event handler? [duplicate]

Possible Duplicate:
Is there a downside to adding an anonymous empty delegate on 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 downsides of assigning an empty delegate to this event? This would save the if !=null condition everywhere, where the event is fired. Of course, this only applies, when the we cannot guarantee that the event is always assigned a proper delegate.

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

Sure, there's a slight performance hit, but it makes the code much cleaner. What's the best practice in such a case? Any technical disadvantages?

like image 492
knittl Avatar asked May 24 '12 11:05

knittl


2 Answers

Interesting idea, I've never thought of doing that. The way i do my custom events is i make a OnCustomEventName taking parameters for the event and just do the check in there for null. and call OnCustomEventName from the code wherever i want the event triggered from. Avoids any performance hits and keeps the operational code cleaner than a 2-line if check every time you want the event fired.

That being said this isn't answering the question about technical disadvantages but more of a best practice when firing events.

example code for threadsafe "On" function.

private void OnCustomEventName()
{
    DelegateName localhandler = CustomEventName;
    if (localhandler != null)
        localhandler();
}
like image 177
Skintkingle Avatar answered Oct 11 '22 12:10

Skintkingle


Instead of adding an empty delegate in the constructor, you can wrap the handler in a function which first checks if the handler is null then calls it. The downside of this is if you have a lot of events, you will have a lot of functions that wrap each event.

private void HandlerWrapper()
{
    Action localHandler = handler;
    if (localHandler != null) handler();
}
like image 1
david.s Avatar answered Oct 11 '22 11:10

david.s