1

I have a setter for a list which is not firing. Adding a breakpoint doesn't even halt execution, it's like it's just not running the code at all. Any tips or advice on why it's not working?

private List<OrderLine> _orderLines = new();

public List<OrderLine> OrderLines
    {
        set
        {
            // Adding a breakpoint here has no effect,
            // and the NotifyPropertyChanged function
            // doesn't get called either
            if (value != this._orderLines)
            {
                this._orderLines = value;
                Recalculate();
                NotifyPropertyChanged();
            }
        }
        get
        {
            return this._orderLines;
        }
    }

    ...
    
    // I am adding to the order lines like this
    order.OrderLines.Add(line)
  • 4
    `order.OrderLines.Add(line)` calls the getter not the setter. – 001 Aug 23 '22 at 13:53
  • Oh really? That seems counter intuitive as I'm not requesting the List, I'm adding to it. – Phill Morgan Aug 23 '22 at 13:55
  • 3
    "That seems counter intuitive as I'm not requesting the List, I'm adding to it." - You are calling an `Add` method on the `List` instance returned from the `get` property of member `OrderLines`. A property setter is used in assignment of the member (when you use the `=` symbol and the property is on the left of the `=` symbol). – Igor Aug 23 '22 at 13:55
  • To call the setter you would need something like `order.OrderLines = new List();` – 001 Aug 23 '22 at 13:55
  • Right, so I presume you can tell what I'm trying to do (trigger the PropertyChanged event when an item is added to the property). Would you say there is a better way to achieve this? – Phill Morgan Aug 23 '22 at 13:57
  • 3
    Thate depends: Are you interested in when the collection instance changes (add, remove, etc) or when a new collection is assigned? If you want to know about changes to the existing collection see `ObservableCollection`: https://stackoverflow.com/q/4279185/1260204 – Igor Aug 23 '22 at 13:58
  • 1
    Thanks igor, yes I'm interested in triggering a function (Recalculate) and an event when the collection instance changes. I'll take a look into ObservableCollection. – Phill Morgan Aug 23 '22 at 14:01

1 Answers1

0

The setter will only be called if you use order.OrderLines = new List<OrderLine>() then the setter will be called otherwise you get the Value from it with the getter.

SoulB
  • 68
  • 7