Cleaning up INotifyPropertyChanged

Dec 10, 2008

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!

Posted by admin | Categories: Uncategorized |

Share with others

No Responses so far | Have Your Say!

Leave a Feedback

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>