Possible Duplicate:
When are Getters and Setters Justified
Why are public and private accessors considered good practice?
In my time as developer I learned that properties can be very useful. I use properties to control read and write access or to add something like validation checks.
But assuming that I have an auto property with a public getter and setter.
public string LastName { get; set; }
In that case I don’t see any point in using properties over fields.
I could also do following:
public string LastName;
Is there anything that speaks against a public field in this case?
Why should I use a property?
1
In general, yes, using public fields instead of properties is a bad practice.
The .NET framework by and large assumes that you will use properties instead of public fields. For example, databinding looks up properties by name:
tbLastName.DataBindings.Add("Text", person, "LastName"); // textbox binding
Here are some things you can easily do with properties but not with fields:
-
You can add validation (or any other code, within reason) to values in a property:
private string lastName; public string LastName { get { return lastName; } set { if(string.IsNullOrEmpty(value)) throw new ArgumentException("LastName cannot be null or empty"); lastName = value; } }
-
You can easily change accessibility levels for getters and setters:
public string LastName { get; private set; }
-
You can use them as part of an interface definition or an abstract class.
If you start out with public fields and assume it’ll be easy to change to properties later, you will likely run into trouble. If you have any code in other assemblies that depends on accessing your public fields, you will have to rebuild and redeploy all of them if you switch to property-based access. You might also have code that uses reflection to get at the values… that’d also need to be changed.
And if you’re really unlucky, those changes would have to be made in a part of the codebase you have no control over and you’ll be stuck hacking around public fields.
For more gory details, check out item 1 in the first chapter of Effective C# by Bill Wagner.
The setters and getters can be modified without making breaking API changes. This is the primary reason for using properties over fields. If you know without a doubt that you will not need to modify the getter/setter, then you might be ok, but why risk it? After all, it is not like it is that big of an inconvenience to make it a property.
2
It’s bad because you’re exposing the internal state of your object, and you don’t have any control over how that state is changed. With getters and setters, you can at least inspect the data and modify it if necessary, so your object’s internal state remains consistent (and valid).
1