Is it possible to create a clone of an object, with an attached event handler, when implementing the IClonable interface. For example:

 public class A : IClonable, //INPC { //... } public class B : IClonable { public A PropA { get; set; } public B() { PropA.PropertyChanged += a_PropertyChanged; } private void a_PropertyChanged() { //... } public object Clone() { // ???? return new B() { PropA = this.PropA.Clone() }; } } 

In this case, clone B created does not have an event subscription.
Is there a better option than to re-subscribe to an event in a new object?

    2 answers 2

    This construction should not work either in the clone or in the original object:

     public A PropA { get; set; } public B() { PropA.PropertyChanged += a_PropertyChanged; } 

    At the time the constructor is PropA property PropA still null - therefore it is impossible to subscribe to the event.

    In reality, you apparently use another constructor to create an object B - that's why everything works. But when cloning stops.

    There are two ways to fix the situation.

    Method one.

    The property should be made immutable in order to exclude the random assignment of a value outside the constructor (this assignment will not work correctly anyway):

     public A PropA { get; } public B (A argA) { PropA = argA; PropA.PropertyChanged += a_PropertyChanged; } 

    When cloning an object, you must use the same constructor as at creation.

    The second way.

    Subscribing to an event should be done in the mutator properties:

     private A fieldA; public A PropA { get { return fieldA; } set { if (fieldA != null) fieldA.PropertyChanged -= a_PropertyChanged; fieldA = value; if (fieldA != null) fieldA.PropertyChanged += a_PropertyChanged; } } 

    In this case, the object B will listen to events from the "connected" object A, regardless of who and how many times he reinstalled PropA to it.

      In class A you need to add in the Clone() function so that event handlers are also reassigned:

       class A: IClonable { public object Clone() { A tt = new A(); tt.PropertyChanged = this.PropertyChanged; return tt; } } 
      • This will send the event to the original object B, and not to its clone. - Pavel Mayorov pm
      • The construction is not correct. PropertyChanged can only be on the left side - = or + =. - Gardes