Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# why shall I use "new" keyword when subscribing for an event?

What is the difference between following 2 ways of subscribing for an event?

receiver.ConfigChanged += Config_ConfigChanged;

receiver.ConfigChanged += new EventHandler(Config_ConfigChanged);

It seems that both of them work the same way but if so, what is the point of using the second one?

What about unsubscribing, will both following methods work also the same way?

receiver.ConfigChanged -= Config_ConfigChanged;

receiver.ConfigChanged -= new EventHandler(Config_ConfigChanged);
like image 882
kmalmur Avatar asked Dec 09 '22 05:12

kmalmur


1 Answers

The verbose way works in all versions of C#, the short way only in C# 2 and later. So I see no reason to use the long way nowadays.

There are some situations where you still need to use new DelegateType(methodGroup), but event subscribing isn't one of them. These situations usually involve generic type inference or method overloading.

Unsubscribing will work either way since it is based on value equality, not referential equality. If I recall correctly both the implicit conversion from a method group and the explicit new get translated to the same IL code. The implicit conversion is just syntax sugar.

like image 122
CodesInChaos Avatar answered May 18 '23 00:05

CodesInChaos