Alex Rivera | Logout

C# getter and setter shorthand

Asked 2011-02-15T21:36:50.883
16

If my understanding of the internal workings of this line is correct:

public int MyInt { get; set; }

Then it behind the scenes does this:

private int _MyInt { get; set; }
Public int MyInt {
    get{return _MyInt;}
    set{_MyInt = value;}
}

What I really need is:

private bool IsDirty { get; set; }

private int _MyInt { get; set; }
Public int MyInt {
    get{return _MyInt;}
    set{_MyInt = value; IsDirty = true;}
}

But I would like to write it something like:

private bool IsDirty { get; set; }

public int MyInt { get; set{this = value; IsDirty = true;} }

Which does not work. The thing is some of the objects I need to do the IsDirty on have dozens of properties and I'm hoping there is a way to use the auto getter/setter but still set IsDirty when the field is modified.

Is this possible or do I just have to resign myself to tripling the amount of code in my classes?

Edit
Report

1 Answer

1

I have created a custom Property<T> class to do common operations like that. I haven't used it thoroughly yet though, but it could be used in this scenario.

Code can be found here: http://pastebin.com/RWTWNNCU

You could use it as follows:

readonly Property<int> _myInt = new Property<int>();
public int MyInt
{
    get { return _myInt.GetValue(); }
    set { _myInt.SetValue( value, SetterCallbackOption.OnNewValue, SetDirty ); }
}

private void SetDirty( int oldValue, int newValue )
{
    IsDirty = true;
}

The Property class handles only calling the passed delegate when a new value is passed thanks to the SetterCallbackOption parameter. This is default so it can be dropped.

UPDATE:

This won't work apparently when you need to support multiple types (besides int), because the delegate won't match then. You could ofcourse always adjust the code to suit your needs.

answered 2011-02-15T21:50:19.907

Your Answer