Search code examples
c#winformsmulticastdelegate

Difference between new KeyEventHandler(Form1_KeyDown) and Form1_KeyDown


In a windows forms application you can register event handlers like this:

          this.KeyDown += new KeyEventHandler(Form1_KeyDown);

and later unregister the same handler like this:

          this.KeyDown -= new KeyEventHandler(Form1_KeyDown);

To me this seems odd because I would expect the -= to require the same handler that was registered originally, not a second new handler of the same signature. But from experience I know this works. This led me to think that this was a special case and in reality

          Form1_KeyDown == new KeyEventHandler(Form1_KeyDown)

Based on that theory I have often rewritten my code to register and unregister events like this:

          this.KeyDown += Form1_KeyDown;

Is this safe? Or will this have some unintended side effect I don't realize?


Solution

  • It is identical, the compiler knows that it must create a new instance of the KeyEventHandler delegate from the event type. And automatically generates the code for it. Feel free to use it, it is crystal clear to anybody that reads your code.

    Even the statement with the new operator is syntax sugar, the MulticastDelegate constructor takes two arguments, not one like the statement suggests, the Target (this) and the Method. The compiler automatically figures out the target. Understanding that a event subscription adds a reference to your object is important, it is a common source of leaks.

    The += operator is syntax sugar too, it is translated to a call to add accessor method of the event. Similarly, the -= operator is translated to a call to the remove accessor. Lots of plumbing that's intentionally hidden.

    Last but not least, you are doing it wrong. You should override the form's OnKeyDown() method instead. It doesn't make sense for a class to listen to its own events, they are meant for other, unrelated code. That was a bit unlucky.