One thing I am concerned with is that I discovered two ways of registering delegates to events.
- OnStuff += this.Handle;
- 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?
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).
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.
I was under the impression that 2 is just syntax sugar. They should be exactly the same thing.
If I remember correctly, the first alternative is merely syntactic sugar for the second.