Removing events

  • Thread starter Thread starter Bob Rundle
  • Start date Start date
B

Bob Rundle

I have the following code, which appears to be working. However it doesn't
look right. The part I am wondering about is the logic in
DisconnectEvents(). This logic creates a new delegate and then expects to
find that delegate in the list of event handlers.

What is the proper way of writing this?

Regards,
Bob Rundle


public void ConnectEvents(joaCollectionEvents events)
{
OnChanged += new OnChangedDelegate(events.OnChanged);
OnAdded += new OnAddedDelegate(events.OnAdded);
OnRenamed += new OnRenamedDelegate(events.OnRenamed);
OnRemoved += new OnRemovedDelegate(events.OnRemoved);
}

public void DisconnectEvents(joaCollectionEvents events)
{
OnChanged -= new OnChangedDelegate(events.OnChanged);
OnAdded -= new OnAddedDelegate(events.OnAdded);
OnRenamed -= new OnRenamedDelegate(events.OnRenamed);
OnRemoved -= new OnRemovedDelegate(events.OnRemoved);
}
 
Bob Rundle said:
I have the following code, which appears to be working. However it doesn't
look right. The part I am wondering about is the logic in
DisconnectEvents(). This logic creates a new delegate and then expects to
find that delegate in the list of event handlers.

What is the proper way of writing this?

That's fine. So long as it's got the same target as the original
delegate, and the same method, it'll match.

(If you'd changed the value of "events", for example, nothing would
have been removed.)
 
Hi Bob,


You could also keep a reference to the added delegates:

OnChangedDelegate ocHandler = null;

public void ConnectEvents(joaCollectionEvents events)
{
ocHandler = new OnChangedDelegate(events.OnChanged);
OnChanged += ocHandler;
}

public void DisconnectEvents(joaCollectionEvents events)
{
if ( ocHandler!= null )
OnChanged -= ocHandler;
}


Cheers,
 

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

Back
Top