Property setters and side effects

I ran into this little problem last week. I had a class with some properties and they were implemented like this:

class Foo
{
    private int _bar;

    public int Bar
    {
        get
        {
            return this._bar;
        }
        set
        {
            this._bar = value;
            this.DoSomeThing();
        }
    }

    private void DoSomeThing()
    {
        /* blah */
    }
}

Setting the value of Bar to something triggers DoSomeThing, whether the value of _bar is changed or not. (setting _bar to 5 when it is 5 will still trigger DoSomeThing, for example a UI refresh).

You can avoid this by doing this in your property:

class Foo
{
    private int _bar;

    public int Bar
    {
        get
        {
            return this._bar;
        }
        set
        {
            if (this._bar != value)
            {
                this._bar = value;
                DoSomeThing();
            }
        }
    }

    private void DoSomeThing()
    {
        /* blah */
    }
}

This makes sure that you don’t execute the value when the value hasn’t changed.

This occurs in particular in Excel when trying to update the CurrentPageName of a DataField in a PivotTable. I need to check if the value has changed, and then, if it has changed, assign it.