Encapsulating Data with 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 is ideal. The client wants direct access to the state of the object and does not want to work with methods. The class designer, however, wants to hide the internal state of his class in class members, and provide indirect access through a method.
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 original
Hour member variable, the change to computing the
value would break the client. By decoupling and forcing the client to
go through a method (or property), the Time class
can change how it manages its internal state without breaking client
code.
Properties meet both goals: they provide a simple interface to the client, appearing to be a member variable. They are implemented as methods, however, providing the data hiding required by good object-oriented design, as illustrated in Example 4-11.
Example 4-11. Using a property
public class Time { // public accessor methods public void DisplayCurrentTime( ) { System.Console.WriteLine( "Time\t: {0}/{1}/{2} {3}:{4}:{5}", month, ...