VBCorLib for VB6

Monday, November 21, 2005

Is It An Object?

Sometimes I keep all kinds of values in a Collection, Hashtable, ArrayList, you get the idea. When I go to access the value I may not know if that particular item is an object or a value type. I mean, I need to use Set if it's an object. This comes up when I might have created a wrapper collection and need to be able to return the inner collection item. Some how I need to be able to test the return value type for the inner collection to properly return the value from my wrapper collection.

VBCorLib provides a couple of easy ways to assign a value to a Variant datatype without knowing the datatype.

CopyVariant and MoveVariant.

These both do what they say. CopyVariant makes a copy, leaving the original value in the original variable. Any datatype can be copied into a variant without knowledge of the type being copied. This means you do not have to check if the value is an object. The Set method is not needed.

MoveVariant, however, actually moves the bytes from the original variable to the destination variable. This prevents all the overhead required to make a copy of a value if you don't need the original variable to have the value anymore. As stated, since all 16 bytes are moved, then the source variable needs to be of type Variant as well. This also means that the subtype of the original Variant does not need to be known since this is a direct memory copy, eliminating the need to worry about using Set.

These functions are globally available, so they can be called directly in code without having to instantiate anything.

So if a value is being returned through a Variant datatype from a collection, the following call can be used:

Public Property Get Value(ByVal Index As Long) As Variant
MoveVariant Value, mList(Index)
End Property

Sometimes I want to use the value locally, but need to do something different if the value is an object. I could get the value from the collection twice, first testing if it is an object, but this is added overhead. You just want the value, then test if it is an object.

Private Sub SomeMethod()
Dim v As Variant
MoveVariant v, mItems(mIndex)
If IsObject(v) Then
' Do object stuff
End If
End Sub

This simply allows you to get the value once and procede without requerying the collection.

This is one of the little ways that VBCorLib makes things easier for me when programming in VB6.

-Kelly