Can anyone clearly articulate when you use a field and when to use a property in class design?
Consider:
public string Name;
Or:
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
I realize that the second method is more proper and flexible, so that's what I try to use, generally.
But then why do I see people use the first method? Are they just lazy, or is there some specific situation where it's the correct choice? Is it just a matter of preference?
Using properties you can control it's security:
Properties gives easy way to raise events:
Also I often use code like this:
Properties are more maintainable than fields, you can encapsulate logic in your setters/getters, allowing you to hide the implementation.
They also make refactoring easier.
More information:
Just some additional information to Alan's reply:
is the same as
If you want to disallow the set function of Name, you can have
public string Name {get; private set;}
When you make the field public, you allow the user to do whatever they want to do to the field. They can assign unexpected values, invalid values, values that can cause overflow, etc.
With the property, you have control over whether to allow the setting of new values to the field, massaging the value before storing it, notifying interested parties about the change of the field's value, etc. And the same idea for returning value through the getter. For .NET framework from 2.0 up, you can set the accessor for the getter, setter. Say, you only want the user to only have read access to the field, then you make the getter public, but the setter private or protected.
In addition to the already-given reasons for preferring properties, there's also lots of cool stuff in System.ComponentModel to do with data binding and change notification that only works with properties, rather than fields. For example, look at the documentation around PropertyChangedHandler.
A property like defined above acts like a getter and setter. The only benefits of using a property is that you can treat it like a variable with access restriction.
This property can be accessed publicly, but can only be set privately. (You wouldn't want anyone changing your name with out your consent now would you! ;) )