Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 959
Jose Avatar asked Apr 22 '11 14:04

Jose


2 Answers

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.

like image 80
Konrad Rudolph Avatar answered Oct 03 '22 02:10

Konrad Rudolph


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

like image 45
TheHolyTerrah Avatar answered Oct 03 '22 02:10

TheHolyTerrah