Search code examples
delphigenericstype-conversiondelphi-xe7

Converting a generic type variable to string


I'm trying to convert a generic variable of type T into string.

  TMyTest = class
    class function GetAsString<T>(const AValue : T) : string; static;
  end;

...

uses
  System.Rtti;

class function TMyTest.GetAsString<T>(const AValue : T) : string;
begin
  Result := TValue.From<T>(AValue).ToString();
end;

It works good using several types (like Integer, Double, Boolean...) but it "fails" using Variant variables.

procedure TForm1.FormCreate(Sender: TObject);
var
  Tmp : Variant;
begin
  Tmp := 123;

  ShowMessage(TMyTest.GetAsString<Variant>(Tmp));
end;

It produces the following output:

(variant)

I was expecting the same output obtained by the VarToStr function (But I cannot use that function with generic variables):

123


Solution

  • You can check whether T is variant and then use VarToStr on AsVariant function.

    You can easily extend that function to cater for other types where ToString will not give you expected result.

    uses
      System.TypInfo, System.Rtti;
    
    class function TMyTest.GetAsString<T>(const AValue : T) : string;
    begin
      if PTypeInfo(TypeInfo(T)).Kind = tkVariant then
        Result := VarToStr(TValue.From<T>(AValue).AsVariant)
      else
        Result := TValue.From<T>(AValue).ToString();
    end;