Name

Variant Type

Syntax

type Variant;

Description

The Variant type is a dynamic type. A Variant variable can change type at runtime, sometimes storing an integer, other times a string, and other times an array.

Delphi automatically casts numbers, strings, interfaces, and other types to and from Variants as needed. You can also use a number of functions to further manipulate and work with Variants.

Chapter 6, lists all the possible types for a Variant.

Tips and Tricks

  • Variants offer flexibility, but you pay a performance price. Even simple arithmetic with Variants is much more complicated and time-intensive than arithmetic with typed variables. Every reference to a Variant must be checked at runtime, which can be costly if your program often uses Variants.

  • Variants are usually easy to understand and use, but they have some subtleties. For example, Unassigned and Null represent distinctly different Variant values and concepts. One way to think of the difference is to imagine a Variant as a box that contains a piece of paper. On the paper is written the Variant’s value: a number, a string, the time of day, etc. Null is a blank piece of paper. Unassigned is an empty box.

  • To convert a TDateTime to or from a Variant, you must use the functions VarFromDateTime and VarToDateTime.

  • The most common use for Variants is calling an OLE automation server when you don’t have a dispinterface at compile time. You call the server’s methods, but Delphi cannot look up the methods at compile time, so it checks ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.