views:

1288

answers:

3

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?

+10  A: 

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
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
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
I stand corrected. Thanks.
Hamish Smith
A: 

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

Marc Gravell
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
A: 

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