Using EqualityComparer.Default , you can reduce the property setting code to one line as follows:
private int unitsInStock; public int UnitsInStock { get { return unitsInStock; } set { SetProperty(ref unitsInStock, value, "UnitsInStock"); } } public event PropertyChangedEventHandler PropertyChanged; protected void SetProperty<T>(ref T field, T value, string name) { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } }
If your view models are inherited from the base class that defines the SetProperty method and the PropertyChanged event, then the amount of code needed to support INotifyPropertyChanged in your child’s view models becomes very minimal (1 line).
This approach is more detailed than the code weaving techniques mentioned in other answers, but does not require you to modify your build process to execute it.
Do not forget to look at the upcoming C # 5 attributes of caller information , and it also seems that they will allow us to avoid using the magic string in the method without the cost of executing the reflection.
UPDATE (March 1, 2012):
There is no beta version of .NET 4.5, and with it you can refine the code above to remove the need for a string literal in the caller:
private int unitsInStock; public int UnitsInStock { get { return unitsInStock; } set { SetProperty(ref unitsInStock, value); } } public event PropertyChangedEventHandler PropertyChanged; private void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "") { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } }
I have a blog post that talks about this in a bit more detail.
source share