About this task
Assigning to VariantsBefore a Variant has been assigned a value, it is considered empty. Thus, immediately after declaration, the VarType function will return ebEmpty. An uninitialized variant is 0 when used in numeric expressions and is a zero-length string when used within string expressions.A
Variant
is
Empty
only after declaration and before assigning it a value. The only way for a
Variant
to become
Empty
after having received a value is for that variant to be assigned to another
Variant
containing
Empty
, for it to be assigned explicitly to the constant
Empty
, or for it to be erased using the
Erase
statement.When a variant is assigned a value, it is also assigned that value's type. Thus, in all subsequent operations involving that variant, the variant will behave like the type of data it contains.Operations on VariantsNormally, a Variant behaves just like the data it contains. One exception to this rule is that, in arithmetic operations, variants are automatically promoted when an overflow occurs. Consider the following statements: Dim a As Integer,b As Integer,c As Integer
Dim x As Variant,y As Variant,z As Variant
a% = 32767
b% = 1
c% = a% + b% 'This will overflow.
x = 32767
y = 1
z = x + y 'z becomes a Long because of Integer overflow.
In the above example, the addition involving
Integer
variables overflows because the result (32768) overflows the legal range for integers. With
Variant
variables, on the other hand, the addition operator recognizes the overflow and automatically promotes the result to a
Long
.Adding VariantsThe + operator is defined as performing two functions: when passed strings, it concatenates them; when passed numbers, it adds the numbers.With variants, the rules are complicated because the types of the variants are not known until execution time. If you use +, you may unintentionally perform the wrong operation.It is recommended that you use the
&
operator if you intend to concatenate two
String
variants. This guarantees that string concatenation will be performed and not addition.Variants That Contain No DataA Variant can be set to a special value indicating that it contains no valid data by assigning the Variant to Null: Dim a As Variant
a = Null
The only way that a
Variant
becomes
Null
is if you assign it as shown above.The
Null
value can be useful for catching errors since its value propagates through an expression.Variant StorageVariants require 16 bytes of storage internally:
- A 2-byte type
- A 2-byte extended type for data objects
- Bytes of padding for alignment
- An 8-byte value
Unlike other data types, writing variants to
Binary
or
Random
files does not write 16 bytes. With variants, a 2-byte type is written, followed by the data (2 bytes for
Integer
and so on).Disadvantages of VariantsThe following list describes some disadvantages of variants: