3.7.1 Denition

As of version 1.1, FPC has support for variants. For variant support to be enabled, the variants unit must be included in every unit that uses variants in some way. Furthermore, the compiler must be in Delphi or ObjFPC mode.

The type of a value stored in a variant is only determined at runtime: it depends what has been assigned to the to the variant. Almost any type can be assigned to variants: ordinal types, string types, int64 types. Structured types such as sets, records, arrays, les, objects and classes are not assign-compatible with a variant, as well as pointers. Interfaces and COM or CORBA objects can be assigned to a variant.

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.

Remark: The enumerated type assignment is broken in the early 1.1 development series of the compiler. It is expected that this is xed soon.

A variant can hold an 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.

Remark: The array functionality is broken in the early 1.1 development series of the compiler. It is expected that this is xed soon.