How to remove a given delegate from the delegate invocation list

  • Thread starter Thread starter mehdi
  • Start date Start date
M

mehdi

Hi folks,
Consider the following property of a class:

public AnotherClass AnotherClassValue
{
set
{
if(this.anotherClassInstance != null)
this.anotherClassInstance.Changed -= new
EventHandler(anotherClassInstance_Changed);

this.anotherClassInstance = value;

if(this.anotherClassInstance != null)
this.anotherClassInstance.Changed += new
EventHandler(anotherClassInstance_Changed);
}
}

in which it needs to receive the Changed event of AnotherClass. If the
following line of code is called twice,

this.anotherClassInstance.Changed += new
EventHandler(anotherClassInstance_Changed);

the anotherClassInstance_Changed event handler is also get called
twice. Therefore, I've to register for the Changed event once.
However, I've got no idea how many times the AnotherClassValue
property gets called. Therefore, I've to unsubscribe to the event
(using the -= operator) first.

However, as you see, the code is not really brilliant. Is there any
other solution to the above-mentioned problem?

TIA,
Mehdi
 
That looks about right / normal. The main thing I would change is a
short-circuit at the top:

if(ReferenceEquals(anotherClassInstance, value)) return; // no change

Marc
 
Hi folks,
Consider the following property of a class:

public AnotherClass AnotherClassValue
{
set
{
if(this.anotherClassInstance != null)
this.anotherClassInstance.Changed -= new
EventHandler(anotherClassInstance_Changed);

this.anotherClassInstance = value;

if(this.anotherClassInstance != null)
this.anotherClassInstance.Changed += new
EventHandler(anotherClassInstance_Changed);
}

}

in which it needs to receive the Changed event of AnotherClass. If the
following line of code is called twice,

this.anotherClassInstance.Changed += new
EventHandler(anotherClassInstance_Changed);

the anotherClassInstance_Changed event handler is also get called
twice. Therefore, I've to register for the Changed event once.
However, I've got no idea how many times the AnotherClassValue
property gets called. Therefore, I've to unsubscribe to the event
(using the -= operator) first.

However, as you see, the code is not really brilliant. Is there any
other solution to the above-mentioned problem?

That's pretty-much the way you have to do it. If the caller changes
the property from one value to another, and you've subscribed to
events from the old value, you have to unsubscribe from those events,
then re-subscribe to the events from the new value.
 
Back
Top