3.7.1 Definition

As of version 1.1, FPC has support for variants. For maximum variant support it is recommended to add the variants unit to the uses clause of every unit that uses variants in some way: the variants unit contains support for examining and transforming variants other than the default support offered by the System or ObjPas units.

The type of a value stored in a variant is only determined at runtime: it depends what has been assigned to the variant. Almost any simple type can be assigned to variants: ordinal types, string types, int64 types.

Structured types such as sets, records, arrays, files, objects and classes are not assignment-compatible with a variant, as well as pointers. Interfaces and COM or CORBA objects can be assigned to a variant (basically because they are simply a pointer).

This means that the following assignments are valid:

Type  
  TMyEnum = (One,Two,Three);  
 
Var  
  V : Variant;  
  I : Integer;  
  B : Byte;  
  W : Word;  
  Q : Int64;  
  E : Extended;  
  D : Double;  
  En : TMyEnum;  
  AS : AnsiString;  
  WS : WideString;  
 
begin  
  V:=I;  
  V:=B;  
  V:=W;  
  V:=Q;  
  V:=E;  
  V:=En;  
  V:=D:  
  V:=AS;  
  V:=WS;  
end;

And of course vice-versa as well.

A variant can hold an array of values: All elements in the array have the same type (but can be of type ’variant’). For a variant that contains an array, the variant can be indexed:

Program testv;  
 
uses variants;  
 
Var  
  A : Variant;  
  I : integer;  
 
begin  
  A:=VarArrayCreate([1,10],varInteger);  
  For I:=1 to 10 do  
    A[I]:=I;  
end.

For the explanation of VarArrayCreate, see Unit Reference.

Note that when the array contains a string, this is not considered an ’array of characters’, and so the variant cannot be indexed to retrieve a character at a certain position in the string.