Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Make OnPropertyChanged events safe for refactoring

0.00/5 (No votes)
5 Oct 2011 1  
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 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 strings and suggest them (to rename) if they match solving both the source and target problems mentioned above.

Example of property:

C#
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...

C#
protected void Set<t>(string propertyName, ref T property, T newValue) {...}</t>


...which allows you to check to see if the OnPropertyChanged needs to be called, or even OnPropertyChanging (argh, <rant> useless, it needs to be cancellable )

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here