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.

1
  • possible duplicate of C# Event handlers Commented Jul 6, 2014 at 20:24

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 No, there’s no need for that. -= works fine with either form, too.
2

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

Comments

1

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

Comments

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

3 Comments

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
I didn't down vote you, nor do i see a reason for a down vote
“But if you plan to remove that event handler later, you really should save the delegate.” – no, why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.