#794 – A Better INotifyPropertyChanged Implementation

When implementing INotifyPropertyChanged, you need to pass the property name as a string in the PropertyChangedEventArgs object.  This can lead to subtle bugs in your code.  If you happen to spell the property name wrong, the client will be notified about the wrong (non-existent) property and the compiler won’t warn you that there is a problem.

If you use C# 5.0 and target the .NET Framework 4.5, there’s an easier way.  You can use the CallerMemberName attribute to avoid having to pass the property name as a string.

        private int age;
        public int Age
        {
            get { return age; }
            set
            {
                if (age != value)
                {
                    age = value;
                    RaisePropertyChanged();
                }
            }
        }

        //-- INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged([CallerMemberName]string prop = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }

Don’t forget to include:

using System.Runtime.CompilerServices;

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #794 – A Better INotifyPropertyChanged Implementation

  1. Pingback: The Daily Six Pack: March 12, 2013 | Dirk Strauss

  2. AMAZING SITE ! THANK YOU FOR THE CHUNKS :)! YOU ARE THE BEST!!

Leave a comment