Copying and Clearing Custom Variants

From RAD Studio
Jump to: navigation, search

Go Up to Defining Custom Variants Index


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 value of the variant, implement the System.Variants.TCustomVariantType.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 value of the variant.

Delphi:

 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 value of a variant, 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 data of the variant.

Delphi:

 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.

Delphi:

 function TComplexVariantType.IsClear(const V: TVarData): Boolean;
 begin
   Result := (TComplexVarData(V).VComplex = nil) or
   TComplexVarData(V).VComplex.IsZero;
 end;

See Also