Variant Open Array Parameters

Variant open array parameters allow you to pass an array of differently typed expressions to a single procedure or function. To define a routine with a variant open array parameter, specify array of const as the parameter's type. Thus procedure DoSomething(A: array of const);

declares a procedure called DoSomething that can operate on heterogeneous arrays.

The array of const construction is equivalent to array of TVarRec. TVarRec, declared in the System unit, represents a record with a variant part that can hold values of integer, Boolean, character, real, string, pointer, class, class reference, interface, and variant types. TVarRec's VType field indicates the type of each element in the array. Some types are passed as pointers rather than values; in particular, long strings are passed as Pointer and must be typecast to string.

The following example uses a variant open array parameter in a function that creates a string representation of each element passed to it and concatenates the results into a single string. The string-handling routines called in this function are defined in SysUtils.

function MakeStr(const Args: array of const): string var

I: Integer; begin

for I := 0 to High(Args) do with Args[I] do case VType of

vtInteger:

Result

= Result

+

IntToStr(VInteger);

vtBoolean:

Result

= Result

+

BoolToStr(VBoolean);

vtChar:

Result

= Result

+

VChar;

vtExtended:

Result

= Result

+

FloatToStr(VExtendedA

vtString:

Result

= Result

+

VStringA;

vtPChar:

Result

= Result

+

VPChar;

vtObject:

Result

= Result

+

VObject.ClassName;

vtClass:

Result

= Result

+

VClass.ClassName;

vtAnsiString: Result := Result + string(VAnsiString);

vtCurrency: Result := Result + CurrToStr(VCurrencyA);

vtVariant: Result := Result + string(VVariantA);

vtInt64: Result := Result + IntToStr(VInt64A);

vtAnsiString: Result := Result + string(VAnsiString);

vtCurrency: Result := Result + CurrToStr(VCurrencyA);

vtVariant: Result := Result + string(VVariantA);

vtInt64: Result := Result + IntToStr(VInt64A);

We can call this function using an open array constructor. For example,

MakeStr(['test', 100, ' ', True, 3.14159, TForm]) returns the string 'test100 T3.14159TForm'.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment