Defining Custom Variants
Go Up to Using the RTL Index
One powerful built-in type of the Object Pascal 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 can't 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:
- Map the storage of the variant's data on to the
- Declare a class that descends from TCustomVariantType. Implement all required behavior (including type conversion rules) in the new class.
- 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.