Lnio Yarschov
Lnio Yarschov

Reputation: 19

How would I invoke setter when modifying properties in C#?

Suppose I have a class Character, which have stats of the class Stat. Specifically each character has a Character.Speed Stat that can be modified. This speed stat is heavily related to a float ActionValue, so modifying it would mean modifying action value (identical to the game Honkai Star Rail https://honkai-star-rail.fandom.com/wiki/Speed). This is how it looks so far:

public class Character {
    private Stat speed;

    public Stat Speed
    {
        get
        { // copies speed cos I think without this it returns a reference instead? correct if wrong
            Stat res = new Stat(flatBonus: speed.FlatBonus, percentageBonus:speed.PercentageBonus, baseValue:speed.BaseValue);
            foreach (var statusEffect in speed.StatusEffects)
            {
                res.AddStatusEffect(statusEffect);
            }

            return res;
        }
        set
        {
            float avOld = ActionValue;
            float spdOld = this.speed.GetFinalValue();
            this.speed = value;
            ActionValue = avOld * spdOld / speed.GetFinalValue();
        }
    }
    // ...
}

The problem with the following is that setter works only when the reference to Speed changes, and not when properties of Speed changes. Is there some c# feature I don't know abt that enables setter to be invoked for members of a property? So not just invoking setter on character.Speed = ...;, but also character.Speed.FlatBonus = ...;.

Upvotes: 0

Views: 80

Answers (0)

Related Questions