contents   index   previous   next



7 basic rules for manipulating Variants

 

Rule 1: Always initialize a Variant before using it.

 

Rule 2: Always initialize a Variant before using it.

 

This is very easy to forget, but if you don’t the chances of your program crashing are almost 100%.

 

Rule 3: Never pass an un-initialized Variant as an argument to another procedure.

 

The called subroutine has no way of knowing if the Variant has been initialized and almost surely will attempt to cast the Variant into another type.

 

Rule 4: Variant arguments can be passed or received by value or by reference.

 

For Variants passed by reference, you pass or receive a pointer to the Variant structure. Variants passed by value are directly passed on the stack. This has important implications in Fortran, because some Fortran compilers (in particular, Lahey/Fujitsu Fortran 95) can only pass or receive arguments by reference.

 

Rule 5: Always destroy (clear) Variants before they go out-of-scope.

 

In other words, you should always clear internal (private) variants before leaving the subroutine that declares them. Use VariantClear to clear a Variant.

 

Rule 6: If you need to change the type of a Variant, use the appropriate Variant procedure, rather than doing it manually.

 

There is nothing to stop you from directly changing the type of a variant by modifying its vt type and assigning a new value to the appropriate field in the shared section of the Variant structure. However, the only way you can be sure that you have done an OLE/COM-conformant conversion is to use the provided procedures.

 

Rule 7: You should always check the type of Variant you receive as an argument to a subroutine.

 

Remember, a Variant can contain almost any type of data. Most likely, your subroutine will only work with a few of those types. The best way to do this checking is by coercing the received variant into a type acceptable by your subroutine (you can use subroutine VariantChangeType for this).

 

Declaring Variants with f90VB