Little INotifyPropertyChanged helper

Most implementations of INotifyPropertyChanged look as following (notice that you have to make sure that the hardcoded PropertyName is spelled correctly):

class MyClass : INotifyPropertyChanged
{
 public event PropertyChangedEventHandler PropertyChanged;

 private int x;

 public int X
 {
  get { return this.x; }
  set
  {
   if (this.x != value)
   {
    this.x = value;
    this.OnPropertyChanged("X");
   }
  }
 }

 [MethodImpl(MethodImplOptions.NoInlining)]
 private void Fire(Delegate del, params object[] args)
 {
  if (del != null)
  {
   foreach (Delegate sink in del.GetInvocationList())
   {
    try { sink.DynamicInvoke(args); }
    catch { }
   }
  }
 }

 protected virtual void OnPropertyChanged( string propertyName )
 {
  this.Fire( this.PropertyChanged, new PropertyChangedEventArgs( propertyName ) );
 }
}

Everytime you refactor a property you also have to make sure to refactor the string with it’s name in the setter method. Here’s a helper method that makes life a little easier:

protected void OnPropertyChanged()
{
 this.OnPropertyChanged(new StackTrace(false).GetFrame(1).GetMethod().Name.Substring(4));
}

This makes the implementation of a property as simple as (No more hardcoded strings to maintain):

 public int X
{
 get { return this.x; }
 set
 {
  if (this.x != value)
  {
   this.x = value;
   this.OnPropertyChanged();
  }
 }
}
  1. ..except that this will potentially break due to inlining during optimization

  2. You’re right, the code would need more MethodImplOptions.NoInlining..

Leave a Comment


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