Click here to Skip to main content
15,886,199 members
Articles / Desktop Programming / WPF
Alternative
Tip/Trick

Make OnPropertyChanged events safe for refactoring

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
5 Oct 2011CPOL1 min read 7.4K   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralYou are correct. It does take time to evaluate the expressi... Pin
Jeremy Hutchinson4-Oct-11 8:51
professionalJeremy Hutchinson4-Oct-11 8:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.