tags:

views:

49

answers:

2

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.

+1  A: 

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;
    }
}
Jens Granlund
this worked so i'm marking is as an answer. though i am considering a refactoring after the answer from Randolpho
mattias
@mattias, I just considered your question and not the implication of your solution in my answer. What Randolpho suggested is probably better.
Jens Granlund
@jens it still helped in the short run. thanks!
mattias
+2  A: 

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.

Randolpho
I thought the same thing when I read the question. Clone() implies you are indeed cloning the object, events and all.
Jerry Fernholz