To limit access to an internal state of an object.
Consider the classic example of a class of geometric shapes. Say, a Circle object. When you set the radius, you may want to automatically calculate the area (which would be a read-only property)
class Circle
{
float radius;
public float Radius
{
get { return radius; }
set { radius = value; area = Math.Pi * radius * radius;}
}
float area;
float Area
{
get { return area;}
}
}
If you allowed direct access to the "radius" data member, you could not update area
when it changed. Further, if you allowed direct access to area
, users could change it willy-nilly without regard for radius
.