Share via


Visual Basic Concepts

Property Procedures vs. Public Variables

Property procedures are clearly such a powerful means for enabling encapsulation that you may be wondering if you should even bother with public variables. The answer, as always in programming, is "Of course — sometimes." Here are some ground rules:

Use property procedures when:

  • The property is read-only, or cannot be changed once it has been set.

  • The property has a well-defined set of values that need to be validated.

  • Values outside a certain range — for example, negative numbers — are valid for the property's data type, but cause program errors if  the property is allowed to assume such values.

  • Setting the property causes some perceptible change in the object's state, as for example a Visible property.

  • Setting the property causes changes to other internal variables or to the values of other properties.

Use public variables for read-write properties where:

  • The property is of a self-validating type. For example, an error or automatic data conversion will occur if a value other than True or False is assigned to a Boolean variable.

  • Any value in the range supported by the data type is valid. This will be true of many properties of type Single or Double.

  • The property is a String data type, and there's no constraint on the size or value of the string.

Note   Don't implement a property as a public variable just to avoid the overhead of a function call. Behind the scenes, Visual Basic will implement the public variables in your class modules as pairs of property procedures anyway, because this is required by the type library.

For More Information   The capabilities of property procedures are explored further in "Putting Property Procedures to Work for You."