Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "new" operator working for detaching a eventhandler using -=?

Tags:

c#

.net

events

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

object.myEvent -= new MyEvent(EventHandler);

I am some how irritated that the new operator is working.

Can some one explain?

Update

I already know that i don't have to use the new operator for detaching events, but it is still the auto complete suggestion in Visual Studio 2010. My real question is how does -= new work for the detach process. How can a new object / delegate match a prior created object / delegate on the += side?

like image 641
Grrbrr404 Avatar asked Dec 12 '11 07:12

Grrbrr404


People also ask

Should I unsubscribe from events c#?

In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler.

How to register an event in c#?

To do this, click the lightning bolt icon in the properties window and you'll see a list of all the events for the selected object. You can just type the name of the event in there and it'll create the code for you.

How are events and delegates associated in the .NET framework?

NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed: A delegate that identifies the method that provides the response to the event. Optionally, a class that holds the event data, if the event provides data.

Which of the following is the built in delegate function for handling events in net?

public delegate void EventHandler(object sender, EventArgs e) is the built-in delegate for event handler so that you don't need to define it separately in your program. EventArgs is also the built-in class for event arguments in . NET.


1 Answers

You don't have to use the new operator. You haven't had to since C# 2.0 came out:

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

This uses a method group conversion to create a delegate from the method group (the name of the method). This isn't just for events, either:

Action<string> writeToConsole = Console.WriteLine;

EDIT: As for how it works:

  • Using -= on an event just ends up calling the "remove" accessor, which typically uses -= on a delegate... (at least effectively)
  • Using -= on a delegate is syntactic 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 (for instance methods)

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

like image 78
Jon Skeet Avatar answered Oct 05 '22 15:10

Jon Skeet