views:

74

answers:

1

I have a class which is serialized to and from an XML file when the user decided to open or save. I'm trying to add the typical functionality where when they try to close the form with un-saved changes the form warns them and gives them the option of saving before closing.

I've added a HasUnsavedChanges property to my class, which my form checks before closing. However, it's a little annoying that my properties have changed from something like this ..

public string Name
{
    get;
   set;
}

to this...

private string _Name;
public string Name
{
    get
    {
         return _Name;
    }
   set
   {
        this._Name = value;
        this.HasUnsavedChanges = true;
   }
}

Is there a better way to track changes to an instance of a class? For example is there some standard way I can "hash" an instance of a class into a value that I can use to compare the most recent version with the saved version without mucking up every property in the class?

+3  A: 

You can reduce the property parts to single lines:

private int _foo;

public int Foo
{
    get { return _foo; }
    set { SetProperty(ref _foo, value); }
}

Add this to your base class:

private bool _modified;

protected void SetProperty<TValue>(
    ref TValue member,
    TValue newValue,
    IEqualityComparer<TValue> equalityComparer)
{
    var changed = !equalityComparer.Equals(member, newValue);

    if(changed)
    {
        member = newValue;

        _modified = true;
    }
}

protected void SetProperty<TValue>(ref TValue member, TValue newValue)
{
    return SetProperty(ref member, newValue, EqualityComparer<TValue>.Default);
}
Bryan Watts
+1, Thats a nice piece of code.
Alastair Pitts