INotifyPropertyChanged in .Net 4.5 – CallerMemberName

When working in WPF the typical property changed notification typically looks something like this…

public bool IsBusy {
  get { return _isBusy; }
  set {
    if (value.Equals(_isBusy)) return;
    _isBusy = value;
    RaisePropertyChanged("IsBusy");
  }
}
private bool _isBusy;

The issue with this is that it uses a magic string and is not particularly refactor friendly. It can be easily improved by using a lambda expression. This gets us the refactor friendliness, but it still is a little ugly.

public bool IsBusy {
  get { return _isBusy; }
  set {
    if (value.Equals(_isBusy)) return;
    _isBusy = value;
    RaisePropertyChanged(() => IsBusy);
  }
}
private bool _isBusy;

The best case would be to not need to raise property changed at all. This is not going to happen, so how about a second best? What if we could just raise property changed without needing to specify the property name at all?

public bool IsBusy {
  get { return _isBusy; }
  set {
    if (value.Equals(_isBusy)) return;
    _isBusy = value;
    NotifyChanged();
  }
}
private bool _isBusy;

With .Net 4.5 and above, this is now possible. Here is a basic implementation of ObservableObject with the new .Net 4.5 CallerMemberName attribute.

/// <summary> Base observable object class. </summary>
public abstract class ObservableObject : INotifyPropertyChanged {

  public event PropertyChangedEventHandler PropertyChanged;
  public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);

  /// <summary> Notify property has changed </summary>
  /// <param name="propertyName">String property name, if not 
  provided, will be picked up from calling member</param>
  protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") {
  if (PropertyChanged != null){
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Happy Coding!