#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;
Advertisements