What is happening with -= and Event delegates ?

B

Barry Mossman

Hi,

What is required to unwire an event ? I wire it with:
this.MyEvent += new MyEventHandler()

Do I need to maintain a handle to the eventhandler created so that I can
detach it ?

The following seems to work, but it doesn't feel right as I seem to be
adding one object, but then removing another:
this.MyEvent -= new MyEventHandler()

What is happening here ?

Thanks

Barry Mossman
 
D

Dave

delegates are not reference based (or at least not stored that way), so
removing a delegate from a delegatelist is as easy as recreating the handler
and removing it from the list using the -= syntax. What I mean by this is
the following:

The Delegate.Equals method which is used to determine if a delegate in the
list is equal to the delegate that you are attempting to remove compare the
method pointers, not the object references. This means that if they are
pointing to the same method then they are equal.

You are doing it correctly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top