Possible Duplicate:
C#: Difference between ‘ += anEvent’ and ‘ += new EventHandler(anEvent)’
There are two basic ways to subscribe to an event:
SomeEvent += new EventHandler<ArgType> (MyHandlerMethod);
SomeEvent += MyHandlerMethod;
What is the difference, and when should I chose one over the other?
Edit: If it is the same, then why does VS default to the long version, cluttering the code? That makes no sense at all to me.
Since there seemed to be some dispute over my original answer, I decided to do a few tests, including looking at the generated code and monitoring the performance.
First of all, here’s our test bed, a class with a delegate and another class to consume it:
First thing to do is look at the generated IL:
So it turns out that, yes, these do generate identical IL. I was wrong originally. But that’s not the whole story. It may be that I’m going off-topic here but I think that it’s important to include this when talking about events and delegates:
Creating and comparing different delegates is not cheap.
When I wrote this, I was thinking that the first syntax was able to cast the method group as a delegate, but it turns out that it’s just a conversion. But it’s completely different when you actually save the delegate. If we add this to the consumer:
You can see that this has very different characteristics, performance-wise, from the other two:
The results consistently come back as something similar to:
That’s nearly a 20% difference when using a saved delegate vs. creating a new one.
Now obviously not every program is going to be adding and removing this many delegates in such a small amount of time, but if you’re writing library classes – classes that might be used in ways you cannot predict – then you really want to keep this difference in mind if you ever need to add and remove events (and I’ve written a lot of code that does this, personally).
So the conclusion of this is, writing
SomeEvent += new EventHandler(NamedMethod)compiles to the same thing as justSomeEvent += NamedMethod. But if you plan to remove that event handler later, you really should save the delegate. Even though theDelegateclass has some special-case code that allows you to remove a referentially-different delegate from the one you added, it has to do a non-trivial amount of work to pull this off.If you’re not going to save the delegate, then it makes no difference – the compiler ends up creating a new delegate anyway.