Visual Basic Concepts

Standard Modules vs. Class Modules

Classes differ from standard modules in the way their data is stored. There is never more than one copy of a standard module’s data. This means that when one part of your program changes a public variable in a standard module, and another part of your program subsequently reads that variable, it will get the same value.

Class module data, on the other hand, exists separately for each instance of the class.

Avoid making the code in your classes dependent on global data — that is, public variables in standard modules. Many instances of a class can exist simultaneously, and all of these objects share the global data in your component.

Static Class Data

Using global variables in class module code violates the object-oriented programming concept of encapsulation, because objects created from such a class do not contain all their data. However, there may be occasions when you want a data member to be shared among all objects created from a class module. For example, you might want all objects created from a class to share a property value, such as the name or version number of your component.

This deliberate violation of encapsulation is sometimes referred to as static class data. You can implement static class data in a Visual Basic class module by using Property procedures to set and return the value of a Public data member in a standard module, as in the following code fragment:

' Read-only property returning application name.
Property Get ComponentName() As String
   ' The variable gstrComponentName is stored in a
   '   standard module, and declared Public.
   ComponentName = gstrComponentName
End Property

You can implement static class data that is not read-only by providing a corresponding Property Let procedure — or Property Set for a property that contains an object reference — to assign a new value to the standard module data member.

Important   When designing a class that uses static data, remember that your component may be providing objects simultaneously to several client applications (if it’s an out-of-process component) or to a client and several in-process components (if it’s an in-process component). All the objects created from the class will share the static data, even if they’re being used by different clients.