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?
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.
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.
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.
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.
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:
-=
on an event just ends up calling the "remove" accessor, which typically uses -=
on a delegate... (at least effectively)-=
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.
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