#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: