7

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.

Jose
  • 10,891
  • 19
  • 67
  • 89
  • possible duplicate of [C# Event handlers](http://stackoverflow.com/questions/26877/c-sharp-event-handlers) – nawfal Jul 06 '14 at 20:24

4 Answers4

7

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Not Exactly. See my answer. Both 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. – Priyank Apr 22 '11 at 14:22
  • @Priyank No, there’s no need for that. `-=` works fine with either form, too. – Konrad Rudolph Apr 23 '11 at 13:22
2

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

TheHolyTerrah
  • 2,859
  • 3
  • 43
  • 50
1

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

Bala R
  • 107,317
  • 23
  • 199
  • 210
0

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

Community
  • 1
  • 1
Priyank
  • 10,503
  • 2
  • 27
  • 25
  • Your point is taken on this, but I agree with other answers in the first post that saving the delegate is a micro-optimization that in **most** situations is unnecessary – Jose Apr 22 '11 at 14:32
  • I didn't down vote you, nor do i see a reason for a down vote – Jose Apr 22 '11 at 18:15
  • “But if you plan to remove that event handler later, you really should save the delegate.” – no, why? – Konrad Rudolph Apr 23 '11 at 13:21