munger
munger

Reputation: 107

Clear All Event subscriptions (Clone linked)

I just implemented Clone from ICloneable and realized that the event subscriptions from my source instance also followed. Is there a good way to clear all those?

Currently I am using a couple of these loops for every event I have to clear everything.

foreach (var eventhandler in OnIdChanged.GetInvocationList())
{
    OnIdChanged -= (ItemEventHandler) eventhandler;
}

foreach (var eventhandler in OnNameChanged.GetInvocationList())
{
    ...

This works fine but clutters the code a bit. Mostly worried to get event dangling.

Upvotes: 5

Views: 1017

Answers (2)

Jens Granlund
Jens Granlund

Reputation: 5070

I think you could just set OnIdChanged = null in your cloned object.

After you have created the clone you just call the ClearEvents method on the clone.

public class ClonedObject
{
    public event EventHandler OnIdChanged;
    public event EventHandler OnNameChanged;

    public void ClearEvents()
    {
        OnIdChanged = null;
        OnNameChanged = null;
    }
}

Upvotes: 2

Randolpho
Randolpho

Reputation: 56409

Presumably, if you truly wanted to clone an object, you wanted to keep those event subscriptions.

If you're cloning objects that shouldn't be subscribed to events, it appears you should consider refactoring your code. Have your controller or similar objects subscribe to the events with a reference to a dedicated data object and have your data objects store that data without referencing the events; clone the data objects and place them in appropriate controller objects as necessary.

Ultimately, I'm suggesting you get around the issue by not subscribing to events to which you don't need to subscribe. Look at the problem space from a different angle.

Upvotes: 2

Related Questions