It is generally desirable to designate the member
variables of a class as
means that only member methods of that class can access their value.
When you prevent methods outside the class from directly accessing
member variables, you’re enforcing
hiding , which is part of the encapsulation of a class.
Object-oriented programmers are told that member variables should be private. That’s fine, but how do you provide access to this data to your clients? The answer for C# programmers is properties. Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method.
This solution is ideal. The client wants direct access to the state of the object. The class designer, however, wants to hide the internal state of the class in class fields and provide indirect access through a method. The property provides both the illusion of direct access for the client, and the reality of indirect access for the class developer.
By decoupling the class state from the method that accesses that
state, the designer is free to change the internal state of the object
as needed. When the
Time class is
first created, the
Hour value might
be stored as a member variable. When the class is redesigned, the
Hour value might be computed or
retrieved from a database. If the client had direct access to the
Hour member variable, changing how that value is resolved ...