Description |
The Variant data type provides a flexible general purpose data type.
It can hold anything but structured data and pointers.
But use with care - there are penalties in performance, potentials for run time errors and poor code clarity when using Variants.
Use VarType in conjunction with VarTypeMask to determine the curent data types a Variant is set to.
Variants are useful in very specific circumstances, where data types and their content are determined at run time rather than at compile time.
|
|
Notes |
Variant strings cannot be indexed.
|
|
Related commands |
Null |
|
A variable that has no value |
PVariant |
|
Pointer to a Variant value |
|
|
|
Example code : Illustrating a few Variant assignments and the resulting data types |
var
myVar : Variant;
begin // Assign various values to a Variant // and then show the resulting Variant type
ShowMessage('Variant value = not yet set');
ShowBasicVariantType(myVar);
// Simple value
myVar := 123;
ShowMessage('Variant value = 123');
ShowBasicVariantType(myVar);
// Calculated value using a Variant and a constant
myVar := myVar + 456;
ShowMessage('Variant value = 123 + 456');
ShowBasicVariantType(myVar);
myVar := 'String '+IntToStr(myVar);
ShowMessage('Variant value = String 579');
ShowBasicVariantType(myVar);
end;
// Show the type of a variant
procedure TForm1.ShowBasicVariantType(varVar: Variant);
var
typeString : string;
basicType : Integer;
begin // Get the Variant basic type : // this means excluding array or indirection modifiers
basicType := VarType(varVar) and VarTypeMask;
// Set a string to match the type
case basicType of
varEmpty : typeString := 'varEmpty';
varNull : typeString := 'varNull';
varSmallInt : typeString := 'varSmallInt';
varInteger : typeString := 'varInteger';
varSingle : typeString := 'varSingle';
varDouble : typeString := 'varDouble';
varCurrency : typeString := 'varCurrency';
varDate : typeString := 'varDate';
varOleStr : typeString := 'varOleStr';
varDispatch : typeString := 'varDispatch';
varError : typeString := 'varError';
varBoolean : typeString := 'varBoolean';
varVariant : typeString := 'varVariant';
varUnknown : typeString := 'varUnknown';
varByte : typeString := 'varByte';
varWord : typeString := 'varWord';
varLongWord : typeString := 'varLongWord';
varInt64 : typeString := 'varInt64';
varStrArg : typeString := 'varStrArg';
varString : typeString := 'varString';
varAny : typeString := 'varAny';
varTypeMask : typeString := 'varTypeMask';
end;
// Show the Variant type
ShowMessage('Variant type = '+typeString);
end;
|
Show full unit code |
Variant value = not yet set
Variant type = varEmpty
Variant value = 123
Variant type = varByte
Variant value = 123 + 456
Variant type = varInt64
Variant value = String 579
Variant type = varString
|
|