Cleaning up INotifyPropertyChanged
I have always been annoyed by implementing the INotifyPropertyChange interface, which is needed if I want to take advantage of data binding for my class entities. I get annoyed because of how much code is involved in the Setter methods. Here’s an example:
public class Employee : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
I hate all the if (_name != value) conditions that have to be in every setter, not to mention the lack of automatic refactoring since the property name is hard set. Therefore, I was really excited to see this post from my friend Jonathan Fuller and his much cleaner way of implementing INotifyPropertyChanged.
Be sure to read his entire post, but in a nutshell, by using his implementation, I would be able to cleanup the code above to the following:
public class Employee : NotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(()=> Name, ()=> _name, value); }
}
}
Now that’s the kind of cleaning I like to see!