LTR
LTR

Reputation: 1352

Event unsubscribe / resubscribe on property change

I often write code like that:

MyObject property;
MyObject Property
{
    get { return property; }
    set {
            if (property != null)
                property.Changed -= property_Changed; // unsubscribe from the old value
            property = value;
            property.Changed += property_Changed; // subscribe to the new value
        }
}

I'm looking for an elegant way to make the unsubscribing automatic. Any ideas?

Upvotes: 1

Views: 2075

Answers (3)

Jethro
Jethro

Reputation: 5916

Perhaps using Extensions Methods might be what you are looking for.

You could try something like this.

private MyProperty property;
public MyProperty Property
{
    get { return property; }
    set { property.SubPubValue(value, property_Changed); }
}

private static void property_Changed(object sender, PropertyChangedEventArgs e)
{
    throw new NotImplementedException();
}

public static class Extensions
{
    public static void SubPubValue<T>(this T value, T setValue, PropertyChangedEventHandler property_Changed) where T : MyProperty
    {
        if (setValue != null)
            value.PropertyChanged -= property_Changed;
        value = setValue;
        if (setValue != null)
            value.PropertyChanged += property_Changed;
    }
}

Upvotes: 1

Tigran
Tigran

Reputation: 62276

May be something like this, if you really need to unsubscribe/subscribe on every property change:

MyObject Property
{
    get { return property; }
    set {
            //unsubscribe always, if it's not null 
            if(property !=null)
               property.Changed -= property_Changed;

            //assign value 
            property = value;

            //subscribe again, if it's not null
            if (property != null)                            
                property.Changed += property_Changed; 

        }
}

Upvotes: 2

Tejs
Tejs

Reputation: 41256

That's about as elegant as you can get with the idea you're trying to implement. Of course, you have a logic bug in that value could be null when passed in, and thus property.Changed += property_Changed would explode.

Basically, if you assign a new object, you want to unsubscribe from the old element's event and attach to the new elements event.

Upvotes: 2

Related Questions