Search code examples
c#cloningicloneable

How can I implement a Clone method on an abstract class without using MemberwiseClone?


I have an abstract base class defined like this:

public abstract class BaseItem: INotifyPropertyChanged, ICloneable
{
    // Various Properties...

    public event public event PropertyChangedEventHandler PropertyChanged;

    public object Clone()
    {
        var clone = (BaseItem)MemberwiseClone();
        return clone;
    }
}

The derived classes inherit and use the base class's Clone method so that they don't have to implement their own Clone methods (plus some additional, irrelevant reasons).

Generally, this code works as intended. The only problem is that there is an unwanted side effect. Because I'm using MemberwiseClone to clone the instance, reference types are shallow copied, which unfortunately includes events. So any objects that have subscribed to events on the original instance will also be subscribed to events on the clone instance. This is the problem.

Is there any way that I can make a clone of an instance of a BaseItem-derived class using the BaseItem.Clone method without also cloning events?


Solution

  • As @JohnWu mentioned in the comment, the solution that worked for me was to set the event handler to null to remove all its subscribers.

    public abstract class BaseItem: INotifyPropertyChanged, ICloneable
    {
        // Various Properties...
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public object Clone()
        {
            var clone = (BaseItem)MemberwiseClone();
            clone.PropertyChanged = null;
            return clone;
        }
    }