Make OnPropertyChanged events safe for refactoring





5.00/5 (1 vote)
Be aware: expressions take a LOT of time to evaluate (relative to a constant string), and will make writing values to properties slow.I think that the solution is to a problem that has limited risk. What I mean is if you need to rename a property, then the call to the OnPropertyChange is...
Be aware: expressions take a LOT of time to evaluate (relative to a constant string), and will make writing values to properties slow.
I think that the solution is to a problem that has limited risk. What I mean is if you need to rename a property, then the call to the useless, it needs to be cancellable )
OnPropertyChange
is nearby in the setter, so it is simple, and obvious to change both at the same time. Also, if you have a backing field, then it should be renamed as well. Of course you can avoid this by using a Dictionary
, but that slows down reads as well. One more thing, you will need to make sure the target of the OnPropertyChange
(which expects a string propertyName
) gets modified as well.
If you feel that you must use expressions, create a separate field for them, and set them once in the constructor, instead of evaluating them each time in the property setter, or use a lazy instantiator.
Alternately:
Refactoring solutions (i.e. Resharper) will look in constant string
s and suggest them (to rename) if they match solving both the source and target problems mentioned above.
Example of property:
public string MyProp {get{return _MyProp;}set{Set("MyProp", ref _MyProp, value);}} string _MyProp;
You could just create a "snippet" of the above.
BTW, the Set
methods signature is...
protected void Set(string propertyName, ref T property, T newValue) {...}
...which allows you to check to see if the OnPropertyChanged
needs to be called, or even OnPropertyChanging
(argh,