RAD Studio
ContentsIndex
PreviousUpNext
Copying and Clearing Custom Variants

In addition to typecasting and the implementation of operators, you must indicate how to copy and clear variants of your custom Variant type. 

To indicate how to copy the variant's value, implement the Copy method. Typically, this is an easy operation, although you must remember to allocate memory for any classes or structures you use to hold the variant's value:

procedure TComplexVariantType.Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else
with TComplexVarData(Dest) do
begin
VType := VarType;
VComplex := TComplexData.Create(TComplexVarData(Source).VComplex);
end;
end;

Note: The Indirect parameter in the Copy method signals that the copy must take into account the case when the variant holds only an indirect reference to its data.
Tip: If your custom variant type does not allocate any memory to hold its data (if the data fits entirely in the TVarData record), your implementation of the Copy method can simply call the SimplisticCopy method.
To indicate how to clear the variant's value, implement the Clear method. As with the Copy method, the only tricky thing about doing this is ensuring that you free any resources allocated to store the variant's data:

procedure TComplexVariantType.Clear(var V: TVarData);
begin
V.VType := varEmpty;
FreeAndNil(TComplexVarData(V).VComplex);
end;

You will also need to implement the IsClear method. This way, you can detect any invalid values or special values that represent "blank" data:

function TComplexVariantType.IsClear(const V: TVarData): Boolean;
begin
Result := (TComplexVarData(V).VComplex = nil) or
TComplexVarData(V).VComplex.IsZero;
end;
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!