#792 – Being Notified When an Object’s Properties Change, Part I

If you write a class, there’s a pattern that you can implement, to let users of your class know when a property value changes.  This pattern is implemented by implementing the INotifyPropertyChanged in your class.

The purpose of this pattern is to let client code know that some property value has changed, in situations where that code didn’t initiate the change.  For example, this pattern is used in data binding.

Below is an example of a class that implements INotifyPropertyChanged.  The class defines an event that is fired whenever any property value changes.

    public class Dog : INotifyPropertyChanged
    {
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    RaisePropertyChanged("Name");
                }
            }
        }

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

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public void AgeThisDog()
        {
            Age++;
        }

        //-- INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

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

Part II of this topic will show how client code can use this new event.

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

3 Responses to #792 – Being Notified When an Object’s Properties Change, Part I

  1. EggaPauli says:

    A slight improvement would be using the CallerMemberNameAttribute introduced in .NET 4.5. Take a look at http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx for details.

    • Sean says:

      Thanks–you’re way ahead of me–I’ve got an upcoming post in the pipeline that explains how to use this attribute to avoid specifying property names as strings.

  2. Pingback: Kana Waa Cashar Danboo Inoo BILAAMI dOONA | Bariisle.wordpress.com

Leave a comment