Clear all event subscriptions (Clone linked)

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

I am currently using a couple of these loops for every event that I have to clear.

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

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

This works great, but clutters up the code a bit. Mostly worried that the event is hanging.

+5
source share
2 answers

I think you could just install OnIdChanged = nullinto your cloned object.

Once you have created the clone, you simply call the method ClearEventson the clone.

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

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

, , .

, , . ; .

, , , . .

+2

All Articles