When I have a class that implements INotifyPropertyChanged, is it ok to expose the implementation as a public method?
For instance, if I have a property called “Sum” on a class, and I want a button click in the UI to update the sum, what is the best way to do this?
Below is some pseudo-code to illustrate what I mean
classinstance.NotifyPropertyChanged("Sum");
...
public Sum {
get { return x + y + z; }
}
In .Net the preferred practice for methods that raise events is for the method to be declared as protected so that it can only be called by derived classes (This is because only the class that declares the event can raise it. In order to raise the event from a derived class a method is required to raise the event).
For example…
This method is then called by the class (or derived classes) in a property setter to indicate that a property has changed, like so…
Other objects can then subscribe to this event and will be notified every time the
MyPropertyproperty is changed.Now, to answer your question as to whether the
OnPropertyChangedmethod can be public. The answer is yes but you should be asking yourself why this would be the case.Why would another class know when a property has changed so that it can call the method? if it already ‘knows’ when the property has changed then you shouldn’t need to subscribe to the property changed event in the first place! Only the class itself should ‘know’ when one of its own properties has changed.
In your example You are notifying that the property ‘sum’ has been changed. but it hasn’t. In fact, your code doesn’t even allow that property to be changed outside of its own class.
I suspect that maybe you want some way of notifying that the sum property needs to be re-evaluated because a dependent property has been changed. If this is the case then you need to raise a property changed event when that dependent property changes.
Imagine that changes to the ‘MyProperty’ property shown earlier also means that ‘Sum’ has changed then that would be handled like this: