Object References Explained

First off, let's explore exactly what an "object" is.  For the purposes of this article, an object is a created in memory instance of a VB class.  When you boil it all down, this means an object is a block of memory that contains all of the code and all of the data associated with the initialized instance of a class (its slightly more complicated than this but this explanation will work for our purposes).  When you create an object in VB, you dimension a variable of the object type and then create an instance of the object.  Each variable in Figure1 now contains a pointer to the beginning of the memory block occupied by the instance of the YourObjectType object.

Figure1

 

Every object must keep a count of how many object variables refer to it at any given time.  Each variable is called a reference to the object and the count is the reference count or "RefCount" on the object.  Each time an object is instantiated, the RefCount is incremented by one for each variable that holds a reference to the object.  This is to make sure that any object is not destroyed before all clients that reference it are finished using the object.  In Figure2, we see that each object has a RefCount of 1.

Figure2

 

In Figure3, we change our references.  See what happens to the RefCount on the object.  The object will remain in existence for as long as the Ref count is greater than zero.

Figure3