Search code examples
c#c#-3.0propertiesautomatic-properties

how to override set in C# of automatic properties


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?


Solution

  • 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();
        }
    }