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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With