Adding an Event Handler

Can someone tell me if there is a difference in the following statements:

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

whenever I press += , the first selection appears when I click the tab, so I always left it. but I wonder if I can just write the second one. I guess they both compiled the same way, but I wonder if this is true. I'm pretty sure that I can just look at the IL, but I'm too lazy for that :) I would just ask.

+7
source share
4 answers

The first option was needed in the first C # compiler. Subsequent versions do not require this - the second is strictly equivalent to the first, and the compiler will deliver a constructor call.

Since the second option is shorter, removes unnecessary redundancy and has no shortcomings, I recommend using it instead of the explicit version. On the other hand, the IDE, unfortunately, offers only intelligent code completion for the first version, so you can just go with it.

+7
source
They are the same. The first statement is deduced by the second and processed for you in the plumbing.
+2
source

They are identical. There is no difference. The second form is essentially an abbreviation for the first, and they will produce identical ILs.

+1
source

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

Link: + = new EventHandler (method) vs + = Method

The difference between '+ = new EventHandler and' - = new EventHandler (anEvent)

0
source

All Articles