Monday 3 February 2014

Variant Data Type in Delphi: Precautions while using variant data types in Delphi

Variant Data Type in Delphi: Precautions while using variant data types in Delphi

The Variant data type provides a flexible general purpose data type. It can hold anything but structured data and pointers. Variants are useful in very specific circumstances, where data types and their content are determined at run time rather than at compile time. 

Basically, once you've declared a variant variable such as the following:

  V: Variant;
you can assign to it values of several different types:

V := 10;
V := 'Hello, World';
V := 45.55;

Once you have the variant value, you can copy it to any compatible-or incompatible-data type. If you assign a value to an incompatible data type, Delphi performs a conversion, if it can. Otherwise it issues a run-time error. In fact, a variant stores type information along with the data, allowing a number of run-time operations; these operations can be handy but are both slow and unsafe.

Why not to use variant data type intensively in Delphi?

In general, you can use variants to store any data type and perform numerous operations and type conversions. But there are penalties in performance, potentials for run time errors and poor code clarity when using Variants. Notice that this goes against the general approach of the Pascal language and against good programming practices. A variant is type-checked and computed at run time. The compiler won't warn you of possible errors in the code, which can be caught only with extensive testing. On the whole, you can consider the code portions that use variants to be interpreted code, because, as with interpreted code, many operations cannot be resolved until run time. This affects in particular the speed of the code.


1. Use VarType in conjunction with VarTypeMask to determine the current data types a Variant is set to. 

2. Variant strings cannot be indexed.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.