Encapsulating Data with Properties

Most of the time, you’ll want to designate the member variables of a class as private. This 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 data hiding, which is an aspect of the encapsulation of a class, as we discussed in Chapter 6.

That’s fine, but if the members are private, how do your other classes access that data? The answer for C# programmers is properties. Properties allow other methods (called clients) to access the state of your class as though they were accessing member fields directly, although you’re actually implementing that access through a class method.

This solution is ideal. The client wants direct access to the state of the object. As the class designer, though, you want to hide the internal state of the class in class fields and provide indirect access through a method. For example, you might want external classes to be able to read a value, but not change it; or you might want to write some code so that the internal field can accept only values in a certain range. If you grant external classes free access to your member fields, you can’t control any of that. The property provides both the illusion of direct access for the client and the reality of indirect access for the class developer.

By separating the class state from the method that accesses that state (a process called decoupling), you’re free to ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.