This question already has an answer here:
I'm working in C# 2.0, but this would apply to most object oriented languages. When I create classes with public properties that wrap private fields, I switch back & forth between whether I should use the property or field internally. Of course C# 3.0 makes this easier with auto-properties, but it could still apply.
Does it matter?
public class Person
{
private string _name = "";
public string Name
{
get { return _name; }
set { _name = value; }
}
public Person(string name)
{
_name = name; //should I use the property or field here?
}
}
You should use "Name" (property), because if you want some checks for this value, you can place it into setter of "Name" property and then will be used for constructor and for lately setting value too.
Normally I use the public properties with some exceptions where I may want to avoid any extra code written in the property accessor. With automatic properties in C#3.0 I rarely create backing fields by hand; typically only when the default value of the automatic backing field is not appropriate for my property.
I would recommend using the property, You never know when you might being doing something inside your property ie. lazy loading, conversion, formatting, calculation, etc. that would introduce a bug if you used the private member...
Basically, because you can implement your validation and other logic in the property, you should access through the property unless you have a specific reason not to.
It helps with consistency within your object, because that way you know that the values of your private fields have gone through whatever rigors you choose to put in your accessor or setter methods.
On the other hand, the constructor can possibly be an exception to this, because you might want to set initial values.
But in general, I'd say access through the property.
EDIT
A (trivial/contrived) example
So in this case, you would want the constructor to skip the property but if you EVER use the field again you'll be causing a bug in your code because you're skipping the 'name archiving'. The reason to put validation in your property is so that you don't need to duplicate the validation code in every place that you access the field, so you shouldn't skip it even in private methods.
Mostly it's like a code preference, but I' prefer to use public properties or ever private properties, you could simply add some logic to property without any changes in caller code. Also in 3.5 .NET you have useful code sugar as autoproperty.
Use the Property. Or better yet, if you're using C# 3.0 or above use Automatic Properties like so:
If you use the property now you'll be ready when you modify your code to use Automatic Properties.