Should you access a variable within the same class via a Property?

If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.

My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for and against as to which is the most correct and why.

Or is it just a matter of coding standards being used on the project?


One of the stronger argument for accessing local (class scope) variables through properties is that you add a level of abstraction in your class. If you change any logic concerning how that field is stored then the rest of your code will be left unaffected.

For example you might change that from a local variable to a property of a child object, to a database call, to a webservice call, to a static property on a class and so on. When making the change it gives you a single point of change, the property, and you do not have to update the rest of your class since they all use the property.

Also using the property enables you to apply business rules on the value of the property instead of having to enforce the same rule at each location where you'd directly access the field. Again, encapsulation

With the introduction of automatic properties there's even less reason to explicitly have a local variable, unless you need to apply business rules on the get/set


It depends on whether you want to apply any logic implemented within the property setter, and so you really have to decide on a case by case basis.

When you go directly to the private field, you know that the field is being set to exactly what you say.

When you go through the Property, the value gets set according to the setter logic, so you get any business rules or validation you want over values assigned to that field.

Pretty hard to come up with a rule about when doing either is 'correct', about the only one I'd say I follow is that in constructor initialisation I'd pretty much never use the Property.