Share via


Visual Basic Concepts

Object References and Reference Counting

The primary rule for object lifetime is very simple: An object is destroyed when the last reference to it is released. However, as with so much of life, simple doesn't always mean easy.

As you use more objects, and keep more variables containing references to those objects, you may go through periods when it seems impossible to get your objects to go away when you want them to.

At some point, it will occur to you that Visual Basic must be keeping track of object references — otherwise how could it know when the last reference to an object is released? You may start thinking that if only you could get access to Visual Basic's reference counts, debugging would be much easier.

Unfortunately, that's not true. To make using objects more efficient, the Component Object Model (COM) specifies a number of complex shortcuts to its reference counting rules. The net result is that you couldn't trust the value of the reference count even if you had access to it.

According to COM rules, the only information you can depend on is whether or not the reference count is zero. You know when the reference count reaches zero, because your object's Terminate event occurs. Beyond that, there's no reliable information to be gleaned from reference counts.

Note   The fact that you don't have to remember the COM reference counting rules is no small thing. Managing reference counts yourself is a lot more difficult than keeping track of which object variables in your program contain references to objects.

Tip   Declare your object variables as class types, instead of As Object. That way, if you have a Widget object that isn't terminating, the only variables you need to worry about are those declared As Widget.

For collections of object references, don't use the Visual Basic Collection object by itself. Object references in a Visual Basic Collection object are stored in Variants — which, like variables declared As Object, can hold references to objects of any class. Instead create collection classes of your own that accept objects of only one class, as described in "Creating Your Own Collection Classes." That way, the only collections you need to search for your Widget object are those of type Widget.

Organize your object into a hierarchy, as described in "Object Models." If all of your objects are connected, It's easy to write a procedure that walks through the whole model and reports on all the existing objects.

Don't declare variables As New. They're like those birthday candles that re-ignite after you blow them out: If you use one after you've set it to Nothing, Visual Basic obligingly creates another object.

For More Information   Circular references are the most difficult kind to shut down cleanly. See "Object Models."