A private field is intended to be only accessible from within the class that it exists.
Why do we use private fields if we can access them from outside their class using properties? Doesn't that defeat the purpose of making a field private?
A private field is intended to be only accessible from within the class that it exists.
Why do we use private fields if we can access them from outside their class using properties? Doesn't that defeat the purpose of making a field private?
Put simply the class will have full control:
SETTER:
To validate arguments, set data alternatives or at worst control / throw an exception.
GETTER:
A value is returned without any scope issues, with guarantees that:
the value is appropriate, default (if not set) and can be controlled depending on class object state.
Otherwise the class object is at risk of having the wrong values set by simply redefining, or at risk of creating bugs if the value must be checked.
In summary, data values can be controlled and quarantined exclusively by the class (or additionally by setting it as protected so extender classes can provide additional functionality).
The idea of having a getter and setter is that you've abstracted some of the logic, and makes it easier if down the line you realize there's extra logic you need to perform when a field is accessed.
Property with a private backing field is useful since you can control the way the private field is accessed through Accessors
It can be explained by a simple example. Assume that you want to represent the day of week as an integer value, then any number higher than 7 will not make any sense. So you can prevent an invalid value using the accessors.
int _dayOfWeek;
public int dayOfWeek
{
get
{
return _dayOfWeek;
}
set
{
if (value > 0 && value < 8) _dayOfWeek = value;
}
}
Of course you can have any kind of logic inside your accessors and hence you have finer control over the private field access. If you declare the field as public, you wont have any control over its access.