Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to add delegates to events with keyword new?

One thing I am concerned with is that I discovered two ways of registering delegates to events.

  1. OnStuff += this.Handle;
  2. OnStuff += new StuffEventHandler(this.Handle);

The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do "OnStuff -= new StuffEventHandler(this.Handle);"? It feels like I am not removing anything at all, since I'm throwing in another StuffEventHandler reference. Does the event compare the delegate by reference? I am concerned I could start a nasty memory pool here. Get me? I don't have the reference to the "new StuffEventHandler" I previously registered.

What is the downside of doing #1?

What is benefit of doing #2?

like image 666
Statement Avatar asked Sep 19 '08 05:09

Statement


2 Answers

Number one is just shorthand that will generate the same MSIL as the 2nd one, at compile type it'll look at this.Handle and infer the delegate to instantiate. But you should never unsubscribe by using new.

So there is no difference between the 2, just some syntactic sugar to make our code cleaner.

like image 110
sontek Avatar answered Sep 21 '22 18:09

sontek


You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool".

When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does not compare the delegate you are removing by reference: it checks for equality by comparing references to the target method(s) that the delegate will call, and removes the matching delegates from "OnStuff".

By the way, "OnStuff" itself is a delegate object (the event keyword that I assume you have in your declaration simply restricts the accessibility of the delegate).

like image 44
Lee Avatar answered Sep 24 '22 18:09

Lee