0

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 = ...;.

Lnio Yarschov
  • 23
  • 1
  • 2
  • When you assign a value to a variable of a _value type_ (which you effectively do (under the covers) when Invoke a setter), the value is copied. When you do _reference type_ assignment, the reference is copied. Classes and strings are reference types, structs, enums and most basic type (like ints and DateTimes) are value types – Flydog57 Aug 23 '23 at 23:09
  • @Flydog57 Thank you for the quick reply, and for clarifying my question. However a way to solve or "hack" the setter to invoke on property members is pretty useful. – Lnio Yarschov Aug 23 '23 at 23:13
  • 1
    You may want to look at `INotifyPropertyChanged` and seeing if shoe-horning it in might help. I can't quite follow what you are talking about, but I'm throwing out ideas at you. – Flydog57 Aug 23 '23 at 23:19
  • Why exactly does the getter seem to make a deep copy? – Fildor Aug 24 '23 at 06:32
  • @Fildor When just returning speed, it returns a reference since its a class object, so modifying the value you receive from the getter modifies the private variable. – Lnio Yarschov Aug 25 '23 at 04:48
  • Why not make Speed immutable, then? – Fildor Aug 25 '23 at 07:24

0 Answers0