Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INotifyPropertyChanging and validations: when do I raise PropertyChanging?

INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values).
If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur.

So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully.

If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change?

What is the contract for this event and what side effects would there be in subscribers?

like image 546
Hamish Smith Avatar asked Oct 04 '08 05:10

Hamish Smith


2 Answers

If your object is given a value that is invalid for the property and you throw an exception then you shouldn't raise the PropertyChanging event. You should only raise the event when you've decided that the value will change. The typical usage scenario is for changing a simple field:

public T Foo
 { get
    { return m_Foo;
    }
   set
    { if (m_Foo == value) return; //no need for change (or notification)
      OnPropertyChanging("Foo");
      m_Foo = value;
      OnPropertyChanged("Foo");
    }
 }
like image 197
Mark Cidade Avatar answered Nov 13 '22 05:11

Mark Cidade


As an aside - PostSharp has the interesting ability to auto-implement INotifyPropertyChanged - like so.

like image 21
Marc Gravell Avatar answered Nov 13 '22 07:11

Marc Gravell