PDA

View Full Version : Variants



Freddy1990
02-27-2007, 07:55 PM
Well, I just got a request from someone who obviously needed variants and i thought I might as well post it so the rest of you who don't know can learn about them :)
A variant is a type that can hold all sorts of types, for example, you can put integer values, extendezd values, strings etc... into variants...
Also, if you put for example an integer, string, boolean, etc in it, you can use it in writeln (direct conversion to string).
You can also store types like TPoint or user-created types in it, but (as far as i know) only for storing them, to use them again you'd need to put them back into the original type.
You could for example also store a variant which holds a boolean in an integer.
If the boolean is true the value will be -1 if it's False it'll be 0.
I hope it helps ;)

TOB
02-27-2007, 08:02 PM
Thanks Freddy, you rock!

Smartzkid
02-27-2007, 08:03 PM
Wow, thanks, been wondering how to use those for a while.

Maybe sometime you could explain how to make our own types?

Also...could a variant hold a variant?

TOB
02-27-2007, 08:08 PM
One thing I might add that I discovered is that if you set the variant to an integer, extended or boolean then attempt to check if it is a string you will be thrown an error that it cannot be converted. To solve this problem use a try and except clause.

Here is an example I just posted in the members' snippets forum.
function empty(v: Variant): Boolean;
begin
try
if(v = '') then
Result:= True;
except
if(v = 0) then
Result:= True;
end;
end;

begin
if(empty(0)) then
Writeln('Empty1');
if(empty('')) then
Writeln('Empty2');
if(empty(False)) then
Writeln('Empty3');
end.