Defining Custom Variants

From RAD Studio
Jump to: navigation, search

Go Up to Defining Custom Variants Index


One powerful built-in type of the Delphi language is the Variant type. Variants represent values whose type is not determined at compile time. Instead, the type of their value can change at run time. Variants can mix with other variants and with integer, real, string, and boolean values in expressions and assignments; the compiler automatically performs type conversions.

By default, variants cannot hold values that are records, sets, static arrays, files, classes, class references, or pointers. You can, however, extend the Variant type to work with any particular example of these types. All you need to do is create a descendant of the TCustomVariantType class that indicates how the Variant type performs standard operations.

To create a Variant type:

  1. Map the storage of the variant data on to the TVarData record.
  2. Declare a class that descends from TCustomVariantType. Implement all required behavior (including type conversion rules) in the new class.
  3. Write utility methods for creating instances of your custom variant and recognizing its type.

The above steps extend the Variant type so that the standard operators work with your new type and the new Variant type can be cast to other data types. You can further enhance your new Variant type so that it supports properties and methods that you define. When creating a Variant type that supports properties or methods, you use TInvokeableVariantType or TPublishableVariantType as a base class rather than TCustomVariantType.