In your first example, Public Fields versus Automatic Properties is a good answer. Basically, you should use always properties instead of fields for non-private
things. This lets you do things like modify the code later without breaking things, and make a private set
. Properties can also do things like notify code when they're changed or provide default or calculated values easily. And you can use auto-properties to cut down on extraneous code:
public int CurrentValue { get; set; }
Your second example is not a good use of properties, since it breaks the assumptions of how properties work. E.g. if I set the property to 3
and no exception is thrown, I'd expect it to be 3
when I get it, not 15
. currentValue = currentValue * 5;
, which could make sense working with a field, property, or local variable, makes the value 5
times larger. Maybe you meant something like this:
int currentBackingValue;
public int CurrentValue
{
get { return currentBackingValue * 5; }
}
Without a set
, this can work nicely, and without breaking any conventions and assumptions: CurrentValue
is calculated based on currentBackingValue
.
(as an aside, you should note that the get
ters and set
ters of a property are, in fact, methods, just used with a field-like syntax to replace something like Java's getX
/setX
standard)