11

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?

Hamish Smith
  • 8,153
  • 1
  • 34
  • 48

3 Answers3

13

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");
    }
 }
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • seeing as you worked on DLINQ (it would have been called that then right?) I guess this is fairly authoritative. Is there any reference you can point me to? – Hamish Smith Oct 04 '08 at 06:14
  • DLINQ was developed by the developer division (which includes the Visual Studio team). The ADO.NET team created LINQ to DataSet and LINQ to Entities. There's a reference at http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic25 – Mark Cidade Oct 04 '08 at 06:25
1

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • that's interesting. I've been using a code snippet (and there's a base class that actually holds the event and raises it) but it does seem to be crying out to be somebody elses problem. – Hamish Smith Oct 04 '08 at 10:49
  • As another aside, this can also be 'auto-implemented' with some rather interesting DI/IOC magic -[seen here](http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code/1532254#1532254) (I'm not sold on this, but it makes interesting pedagogical reading if nothing else) – fostandy Feb 15 '11 at 01:41
0

If you would like to avoid implementing INotifyPropertyChanged altogether, consider using Update Controls .NET instead. This eliminates almost all of the bookkeeping code.

Michael L Perry
  • 7,327
  • 3
  • 35
  • 34