Search code examples
delphidelphi-11-alexandria

How to use array of const with strings?


I'm having an issue with array of const in Delphi 11.3.

I have a function:

MyFunc(test: array of const)

When I call it with integers, I have no trouble getting them back as integers, eg:

MyFunc([2,4,9,0)

and test[0] etc works as expected.

However, if I pass in a string, eg:

MyFunc(['test',9])

I cannot get the string back. The vType returns 17, _Reserved1.

I've looked at as many places as I can, but I'm stuck. Can somebody explain this, and tell me what I'm doing wrong?


Solution

  • In modern Delphi versions, the default string type is UnicodeString.

    Now, the TVarRec documentation does not mention any vType for UnicodeString, but in the System unit there is a vtUnicodeString constant declared, and it has the value of 17.

    That same constant is being used in the TVarRec record for detecting UnicodeString.

    So, it seems that documentation on TVarRec is not up to date.


    You might be wondering why vtString isn't returned in your case. Well, vtString is actually intended for ShortString, which is to be deprecated, or should I say is already deprecated, for any mobile platforms.

    You could also perform the next test scenario and you will see which values are returned for each string type:

    procedure TForm3.Button1Click(Sender: TObject);
    var S1: ShortString;
        S2: AnsiString;
        S3: UnicodeString;
        S4: WideString;
        S5: String;
    begin
      S1 := 'ShortString';
      S2 := 'AnsiString';
      S3 := 'UnicodeString';
      S4 := 'WideString';
      S5 := 'String';
      MyFunc([S1,S2,S3,S4,S5]);
    end;