Encapsulating Data with Properties

It is generally desirable to designate the member variables of a class as Private (using the Private keyword). This means that only member methods of that class can access their value. You make member variables private to support data hiding, which is part of the encapsulation of a class.

Typically, most methods will be public (designated by the Public keyword). The public members of your class constitute a contract between your class and the clients of your class. Any object that interacts with your class is a client. Your public methods promise that if the client calls them with the right parameters, they will perform the promised action. How your methods perform that object is not part of the public contract. That is up to your class.

You can also have some private methods, known as helper methods, whose job it is to do work for methods of your class, but which are not available to clients. The private member variables and private methods are not part of your public contract; they are hidden details of the implementation of your class.

Object-oriented programmers are told that member variables should be private. That is fine, but how do you provide access to this data to your clients? The answer for VB.NET 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 is ideal. The client wants direct access to ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.