Jose
Jose

Reputation: 11091

adding an event handler

Can someone tell me if or what the difference of the following statements is:

MyObject.MyEvent += new EventHandler(MyEventHandlerMethod);
vs.
MyObject.MyEvent += MyEventHandlerMethod;

whenever I press += the first choice pops up when I click tab so I've always left it. but I'm wondering if I can just write the second. I'm guessing that they both get compiled the same, but I'm curious if that's true. I'm pretty sure I could just look at the IL, but I'm too lazy for that :),I'd rather just ask.

Upvotes: 7

Views: 397

Answers (4)

TheHolyTerrah
TheHolyTerrah

Reputation: 2879

They're the same. The first statement is inferred by the second and handled for you in the plumbing.

Upvotes: 2

Priyank
Priyank

Reputation: 10623

So the conclusion of this is, writing SomeEvent += new EventHandler(NamedMethod) compiles to the same thing as just SomeEvent += NamedMethod. But if you plan to remove that event handler later, you really should save the delegate.

Ref: += new EventHandler(Method) vs += Method

Difference between ‘ += new EventHandler’ and ‘ -= new EventHandler(anEvent)’

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 546133

The first variant was necessary in the first C# compiler. Subsequent versions don’t require it – the second is strictly equivalent to the first, and the compiler will supply the constructor call.

Since the second variant is shorter, removes unnecessary redundancy and has no disadvantages, I advise using it, instead of the explicit version. On the other hand, the IDE unfortunately only offers smart code completion for the first version, so you may want to just go with it.

Upvotes: 7

Bala R
Bala R

Reputation: 109027

They are Identical. There is no difference. The second form is essentially a shorthand for the first and they will produce identical IL.

Upvotes: 1

Related Questions