Microsoft Office 2000/Visual Basic Programmer's Guide |
A property sets and stores a characteristic of an object. The simplest way to create a property for a custom object is to add a public module-level variable to the class module. This variable behaves as a property of the object — you can set its value, and then retrieve the value later. A module-level variable in a class module exists as long as an instance of the class exists in memory, so you can count on the property being available for the lifetime of the object.
For example, the following line of code is all that you need to create a property named FirstName within a hypothetical class named Customer:
Public FirstName As String
To set this property, create a new instance of the Customer class and provide a value for the property, as shown in the following code fragment:
Dim cstCust As New Customer
cstCust.FirstName = "Maria"
The property that you create in this manner is always read-write, and there's no way to run other code when you set or return the property's value. Although this is an easy way to create a property when you're first beginning to program with class modules, you'll often find that you want to run code when a property is set or retrieved, or that you need to make certain properties read-only. If you need more control over the property, you can create a Property procedure, discussed in "Creating Scalar Properties" later in this chapter.