Custom Variants in Delphi

I was watching one of the CodeRage presentations the other day.  It was the one about domain specific languages by Marco Cantu.  In it he shows how custom variants can be used to implement a domain specific language in Delphi.  While I found the presentation interesting, I didn’t see much benefit to inventing one and using it in the type of programming that I do.  However, I can see a lot of applications for custom variants.

Unfortunately, Marco didn’t go into a lot of detail about exactly how custom variants are implemented.  So I started reading the Delphi Developers Guide.  It covers the necessary material but I found the explanations to be insufficient and I didn’t have the eureka moment that made everything clear enough to start implementing a custom variant.  So I went to the old standby, Google.  I didn’t find much there either.  One fairly length article that I did find basically parroted the Delphi documentation and examples and wasn’t much help either.

Anyway, I took the information that I could find and the VCL source code and dove in.   As a first project, I decided to implement a custom variant wrapper for the TDataset component that would allow me to access the dataset’s field’s values without have to use the excessively wordy and cumbersome dataset.FieldByName(”field_name“).Value syntax.  I wanted to be able to get a field’s value by using the field’s name as a property, like this, datasetVariant.field_name.  Where field_name is the name of the field in the database.

In a series of articles to follow, I am going to try to document my experiences and discoveries in the hope that; (1) it will serve as a memory aid to me if I ever have to do this again and (2) it will help someone else along the road to their own custom variant.  Wish me luck.

Part 1 - Variant Data Structures
Part 2 - Initializing the Variant
Part 3 - Copying and Clearing the Variant
Part 4 - Implementing Dynamic Properties
Part 5 - Casting the Variant to a Different Data Type
Part 6 - Implementing Dynamic Functions and Procedures

Leave a Reply