tags:

views:

545

answers:

3

Is it appropriate to fire a "property changed" event when the actual value of a property does not change?

public int SomeProperty
{
    get { return this.mSomeProperty; }
    set
    {
        this.mSomeProperty = value;
        OnPropertyChanged(new PropertyChangedEventArgs("SomeProperty"));
    }
}

This will trigger the event even when the new value is identical to the old value. Is this bad practice?

+4  A: 

No, don't fire the event unless the underlying value has actually changed.

Usually, you code the Setter such that it doesn't even bother trying to modify the underlying value unless it actually is different.

Chris Lively
The standard idiom is to check if value is the same as the field underlying the property, returning immediately if it is. Otherwise, the field is updated and the event is triggered.
Steven Sudit
That's what I was trying to say.. ;)
Chris Lively
+4  A: 

If you had an event called PropertySetterAccessed, then it would be appropriate to fire it when the value doesn't change. However, your event is called PropertyChanged, so it should only be fired when that actually happened. If your events/methods/classes etc don't do "what they say on the tin", you are creating a maintenance nightmare for someone.

David M
+4  A: 

Best practice is not to throw the event unless the value changed.

In your case the property is just an 'int', so it's just a simple equality check. If your property was an object in it's own right, there are more cases to consider

  1. You set the same instance again - No property change

  2. You set a different instance with different values - Throw a property change

  3. You set a different, but 'equal' instance ( i.e., the two different objects have the same set of values and can be considered equivalent from your application's point of view ) - Throw a property change.

The last one is subject to some debate... has the property really changed when all of it's attributes are the same? If someone is using that property change to subscribe to changes in the subclass, they will need it to know to unsubscribe from the old class and subscribe to the new one. Therefore I err on the side of announcing the change.

Chris Arguin