how to override set in C# of automatic properties

MhdSyrwan picture MhdSyrwan · Jan 3, 2012 · Viewed 30.3k times · Source

I want to use auto-implemented properties, but at the same time I want to call a method every time the property is changed.

public float inverseMass
{
    get;
    set
    {
        onMassChanged();
        inverseMass = value;
    }
}

Does the previous code make a recursive call to the property? If it does, how to implement this?

Answer

Gary picture Gary · Jan 3, 2012

If you provide your own get/set then you need to provide your own storage for the variable.

private float _inverseMass;

public float inverseMass
{
    get { return _inverseMass; }
    set
    {
        _inverseMass = value;
        onMassChanged();
    }
}