Accessing class member from within the class [closed]
When accessing properties from within a class should you use the private member variable, or the public property?
There actually is an answer to this question, but I believe it is only quite got at by asking another:
Do I get the desired behaviour from utilising the variable, or the property?
Oftentimes a property performs operations on data, meaning you might not get exact same values from one to the other. Generally they do nothing 'expensive', and not to produce side-effects that manifest in other tenuously related elements of the class (properties shouldn't do this,) but one of the benefits of properties is to have a 'mask', so to speak, providing desired getting and setting behaviour which can differ from a direct return or assignment, where variables are the raw, unadulterated data - this is what you'll need to look out for.
For instance, you might find a property for X
never returns null, but the underlying variable can be, and sometimes is null - in this case, your operations might depend on checking for null while the property exposes a 'safe bet' to the outside. So, you must work with the underlying element in this particular case.
Obviously you should strive for some model of consistency in this practice, but the above is the principle, and the practice would mostly be dictated per solution, project, or even class!
If it's something that has a public property that has a setter, I would use that (all else being equal).
In general, from within your class, when there is a property that also itself refers to a private variable, use the private variable from within your class. It is an implementation detail. The purpose of the property is to have a stable outward facing interface.
BUT, in case your property actually does some smart stuff you depend on (like a dependency property), you might choose to always use the property to reuse this smartness.
At least, be consequent in what you're doing, certainly within the scope of a single class, for your implementation to be understandable and maintainable.
In most cases - access private field.
In MVVM view model, or any other class, that implements INotifyPropertyChanged (or similar situation, when it is required by the context), you should access public properties, to have the subscribers notified about value change.
Depends if the propertie has any logic in it: Like validating the input in the setter, or returning a standard value or the like when getting.
And just for those arguments alone, I would suggest to use the propertie. And as allways use private/public wisely.
精彩评论