Variant

From Free Pascal wiki
Revision as of 09:35, 27 July 2016 by FPC user (talk | contribs) (English version of German page.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) polski (pl)

A Variant data type allows a single variable to store values of multiple types. This allows a statically-typed programming language like Free Pascal some of the flexibility normally found only in a dynamically-typed language like Python.

A Variant data type takes more memory than simple data types.The memory requirements of a variant type for 32 bit compilation: 16 bytes or 128 bits. Memory requirements for a variant type in 64 bit compilation: 24 bytes, or 192-bits. Values of any simple data type can be stored in a variant variable. However, operations with the data type Variant are considerably slower than with statically typed simple data type variable.

There are two useful functions for working with Variants in the Variants unit:

  • The VarType() function checks which data type the variant holds.
  • The function VarToStr() converts the value of a variable of type Variant to a string representation.

Definition of a data field of the data type Variant. It is recommended that you use the Variants unit:

Uses 
  Variants;
var
  v: Variant;

Example usage:

Program test_variant;
uses 
  Variants;
var
  v: Variant;
  s: string;
  i: integer;

begin


  // Example:
  // Value assignment:
  v := 1;

  //Examples of permissible type assignments or conversions of variant to a specific data type:

  //Explicit data type conversions:
  s := VarToStr(v);
  Writeln('s:',s);
  s := AnsiString(v);
  Writeln('s:',s);
  i := Integer(v);
  Writeln('i:',i);
  //Implicit data type conversion:
  i := v;
  Writeln('i:',i);

end.