Why does the "new" operator work to detach the event handler using - =?

Why do I need to use the following to detach an event?

object.myEvent -= new MyEvent(EventHandler); 

I'm a little annoyed that the new operator works.

Can someone explain?

Update

I already know that I do not need to use the new operator to detach events, but it is still a completely complete proposal in Visual Studio 2010. My real question is: how - is the new work for the detach process. How can a new object / delegate correspond to a previously created object / delegate on the + = side?

+6
source share
1 answer

You do not need to use the new operator. You haven't had to since C # 2.0 came out:

 foo.SomeEvent += EventHandler; foo.SomeEvent -= EventHandler; 

This uses method group conversion to create a delegate from a method group (method name). This applies not only to events:

 Action<string> writeToConsole = Console.WriteLine; 

EDIT: Regarding how this works:

  • Using -= in an event simply ends with a call to "remove" accessor, which usually uses -= for a delegate ... (at least efficiently)
  • Usage -= for delegate - syntax sugar for Delegate.Remove
  • Delegate.Remove uses delegate equality - two delegate instances are equal if they have the same method and the same target instance (e.g. methods)

Note that using method group transformations will still create a new delegate instance each time you go through the code.

+12
source

Source: https://habr.com/ru/post/903571/


All Articles