[fpc-pascal] How to know the string type of a variable?

Michael Van Canneyt michael at freepascal.org
Mon Dec 30 15:08:59 CET 2013



On Mon, 30 Dec 2013, Marcos Douglas wrote:

> On Mon, Dec 30, 2013 at 9:48 AM, Marcos Douglas <md at delfire.net> wrote:
>> On Mon, Dec 30, 2013 at 9:41 AM, Michael Van Canneyt
>> <michael at freepascal.org> wrote:
>>>
>>>
>>> On Mon, 30 Dec 2013, Marcos Douglas wrote:
>>>
>>>> Hi,
>>>>
>>>> Is possible to know what string type of a variable (AnsiString,
>>>> UTF8String, RawByteString, etc)?
>>>
>>>
>>> You can try
>>>
>>> if TypeInfo(S)=TypeInfo(AnsiString) then
>>>
>>> etc.
>>>
>>> The following program
>>>
>>> procedure t(S : String);
>>>
>>> begin
>>>   if typeinfo(s)=typeinfo(shortstring) then
>>>     Writeln('ShortString')
>>>   else
>>>     Writeln('Ansistring'); end;
>>>
>>> begin
>>>   t('');
>>> end.
>>>
>>> Prints ShortString if compiled as-is (fpc mode), and prints AnsiString if
>>> compiled with -S2h (objfpc mode, string=ansistring)
>>
>> TypeInfo!
>> I was trying using "type(s)", "s is AnsiString"... I forgot.
>>
>> Thank you.
>
> Well, didn't worked as I wanted.
> For example, I know UTF8String is an AnsiString but the TypeInfo
> should catch UTF8String not AnsiString, doesn't?

No. You make a wrong assumption.

TypeInfo will return the DECLARED type of S.

Not the type that was actually passed when calling the routine:
That has been converted to the declared type of S by the compiler 
even before the routine ShowType is called.

Michael.
>
> See the code bellow:
>
> === BEGIN ===
> procedure TForm1.Button1Click(Sender: TObject);
> var
>  AStr: AnsiString;
>  U8Str: UTF8String;
>  UniStr: UnicodeString;
>
>  function  ShowType(S: string): string;
>  begin
>    if TypeInfo(S) = TypeInfo(AnsiString) then
>      ShowMessage('AnsiString')
>    else if TypeInfo(S) = TypeInfo(UTF8String) then
>      ShowMessage('UTF8String')
>    else if TypeInfo(S) = TypeInfo(UnicodeString) then
>      ShowMessage('UnicodeString')
>  end;
>
> begin
>  AStr := 'ábçdé';
>  U8Str := 'ábçdé';
>  UniStr := 'ábçdé';
>
>  ShowType(AStr);
>  ShowType(U8Str);
>  ShowType(UniStr);
> end;
>
> === END ===
>
> The result is:
> AnsiString
> AnsiString
> AnsiString
>
> Regards,
> Marcos Douglas
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>


More information about the fpc-pascal mailing list