views:

234

answers:

4

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?

+2  A: 

I was under the impression that 2 is just syntax sugar. They should be exactly the same thing.

Dested
+8  A: 

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.

sontek
Agree +1, the first way used to be the way to do thing's in .Net v1 and 1.1 , the syntactic sugar was added in v2.
Mendelt
Actually, if you could laborate why I shouldnt unregister by new... It works just the same way. Please attach references to some article if you say I shouldnt unregister with the new keyword
Statement
You are correct, It actually doesn't make a difference, I thought it would have.
sontek
+1  A: 

If I remember correctly, the first alternative is merely syntactic sugar for the second.

Thomas
+4  A: 

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

Lee