Search code examples
c#mathpropertiessetterlimiting

C# Limiting setter value


I'm currently trying to implement properties and in particular limiting my setter. For example, i have a 'Money' float field that i'd like it so you can add/subtract values to it but when it's at 0 make it so that it can no longer be subtracted but it can however still be added to.

I see that in the code below that once 'Money' reaches 0 it'll be always stuck at 0. Is there some way to check whether the setter is being added to? I understand that you can check it in the AddMoney or SubtractMoney methods but was more curious if it's possible to do so in the setter.

public float Money {
    get {
        return this._money;
    }

    set {

        if (_money <= 0){
            _money = 0;
        } else {
            _money = value;
        }
    }
}

void AddMoney(float addAmount){
    Money += addAmount;
}

void SubtractMoney(float subtractAmount){
    Money -= subtractAmount;
}

Solution

  • Try to test if the value is negative don't change the Money value :

            set {
    
                    if (value >= 0)
                    {
                        _money = value;
                    }
                    else
                    {
                    //You may throw exception, or log a warning   
                    }
                }