Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a downside to adding an anonymous empty delegate on event declaration?

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?

like image 528
serg10 Avatar asked Oct 04 '08 19:10

serg10


People also ask

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.

Why do we use anonymous event handlers in Windows Forms?

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.

Why do we need events when we have delegates?

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):

What is the main difference between the event and delegate?

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.


1 Answers

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); 
like image 107
Judah Gabriel Himango Avatar answered Sep 21 '22 20:09

Judah Gabriel Himango