3.7.2 Variants in assignments and expressions

As can be seen from the definition above, most simple types can be assigned to a variant. Likewise, a variant can be assigned to a simple type: If possible, the value of the variant will be converted to the type that is being assigned to. This may fail: Assigning a variant containing a string to an integer will fail unless the string represents a valid integer. In the following example, the first assignment will work, the second will fail:

program testv3;  
 
uses Variants;  
 
Var  
  V : Variant;  
  I : Integer;  
 
begin  
  V:=’100’;  
  I:=V;  
  Writeln(’I : ’,I);  
  V:=’Something else’;  
  I:=V;  
  Writeln(’I : ’,I);  
end.

The first assignment will work, but the second will not, as Something else cannot be converted to a valid integer value. An EConvertError exception will be the result.

The result of an expression involving a variant will be of type variant again, but this can be assigned to a variable of a different type - if the result can be converted to a variable of this type.

Note that expressions involving variants take more time to be evaluated, and should therefore be used with caution. If a lot of calculations need to be made, it is best to avoid the use of variants.

When considering implicit type conversions (e.g. byte to integer, integer to double, char to string) the compiler will ignore variants unless a variant appears explicitly in the expression.