Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# getter and setter shorthand

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?

like image 820
William Avatar asked Feb 15 '11 21:02

William


2 Answers

You'll need to handle this yourself:

private bool IsDirty { get; set; }

private int _myInt; // Doesn't need to be a property
Public int MyInt {
    get{return _myInt;}
    set{_myInt = value; IsDirty = true;}
}

There is no syntax available which adds custom logic to a setter while still using the automatic property mechanism. You'll need to write this with your own backing field.

This is a common issue - for example, when implementing INotifyPropertyChanged.

like image 153
Reed Copsey Avatar answered Oct 24 '22 08:10

Reed Copsey


Create an IsDirty decorator (design pattern) to wrap some your properties requiring the isDirty flag functionality.

public class IsDirtyDecorator<T>
{
    public bool IsDirty { get; private set; }

    private T _myValue;
    public T Value
    {
        get { return _myValue; }
        set { _myValue = value; IsDirty = true; }
    }
}

public class MyClass
{
    private IsDirtyDecorator<int> MyInt = new IsDirtyDecorator<int>();
    private IsDirtyDecorator<string> MyString = new IsDirtyDecorator<string>();

    public MyClass()
    {
        MyInt.Value = 123;
        MyString.Value = "Hello";
        Console.WriteLine(MyInt.Value);
        Console.WriteLine(MyInt.IsDirty);
        Console.WriteLine(MyString.Value);
        Console.WriteLine(MyString.IsDirty);
    }
}
like image 42
Simon Hughes Avatar answered Oct 24 '22 06:10

Simon Hughes