How to check if an object has changed?

You can implement INotifyPropertyChanged interface and if you user VS2010 there is addin that automatic alter all properties in IL (so you don't have to implement it manualy).

I belive there is also some other methods that use Weaving technique.

I found addin in vs2010 gallery:

http://visualstudiogallery.msdn.microsoft.com/bd351303-db8c-4771-9b22-5e51524fccd3

There is nice example - your code:

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string GivenNames { get; set; }
}

What get compiled:

public class Person : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    private string givenNames;
    public string GivenNames
    {
        get { return givenNames; }
        set
        {
            if (value != givenNames)
            {
                givenNames = value;
                OnPropertyChanged("GivenNames");
                OnPropertyChanged("FullName");
            }
        }
    }
}

This is from first resoult from unce G (might be usefull):

http://justinangel.net/AutomagicallyImplementingINotifyPropertyChanged

http://www.codeproject.com/KB/WPF/AutonotifyPropertyChange.aspx


As Sll stated, an dirty interface is definitely a good way to go. Taking it further, we want collections to be dirty, but we don't want to necessarily set ALL child objects as dirty. What we can do, however is combine the results of their dirty state, with our own dirty state. Because we're using interfaces, we're leaving it up to the objects to determine whether they are dirty or not.

My solution won't tell you what is dirty, just that the state of any object at any time is dirty or not.

public interface IDirty
{
    bool IsDirty { get; }
}   // eo interface IDirty


public class SomeObject : IDirty
{
    private string name_;
    private bool dirty_;

    public string Name
    {
        get { return name_; }
        set { name_ = value; dirty_ = true; }
    }
    public bool IsDirty { get { return dirty_; } }
}   // eo class SomeObject


public class SomeObjectWithChildren : IDirty
{
    private int averageGrades_;
    private bool dirty_;
    private List<IDirty> children_ = new List<IDirty>();

    public bool IsDirty
    {
        get
        {
            bool ret = dirty_;
            foreach (IDirty child in children_)
                dirty_ |= child.IsDirty;
            return ret;
        }
    }

}   // eo class SomeObjectWithChildren

Tags:

C#