How to track dirty data in data structure

We’ve all had that scenario where we want to know if data changes in a data structure. This could be done a few different ways. Although, in the .NET Framework it seems to be done one particular way, that’s with INotifyPropertyChanged. With this interface, any downstream consumers or consumers in this class – can monitor if anything changed. Here’s a quick example of how you might implement that:

    public class Customer : INotifyPropertyChanged

    {

        public event PropertyChangedEventHandler PropertyChanged;

 

        public string FirstName

        {

            get { return firstName; }

            set

            {

                firstName = value;

                if (PropertyChanged != null)

                    PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));

            }

        } private string firstName = string.Empty;

 

        public string LastName

        {

            get { return lastName; }

            set

            {

                lastName = value;

                if (PropertyChanged != null)

                    PropertyChanged(this, new PropertyChangedEventArgs("LastName"));

            }

        } private string lastName = string.Empty;

    }

Then, on the consuming side, you can do something like this:

    Customer newCustomer = null;

 

    private void SomeMethod()

    {

        newCustomer = new Customer();

        newCustomer.PropertyChanged += new PropertyChangedEventHandler(newCustomer_PropertyChanged);

    }

 

    private void newCustomer_PropertyChanged(object sender, PropertyChangedEventArgs e)

    {

        Debug.WriteLine("Property " + e.PropertyName + " changed…");

    }

Posted in Best-practices, Uncategorized

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

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 2 other followers

%d bloggers like this: