Search code examples
delphidelphi-xertti

TValue string<-->Boolean back and forth


I'm playing arround with TValue

I've written this code in a blank project:

uses
  RTTI;

procedure TForm1.FormCreate(Sender: TObject);
var
  s: string;
  b: Boolean;
begin
  s := TValue.From<Boolean > (True).ToString;
  b := TValue.From<string > (s).AsType<Boolean>;
end;

But I can not convert back from string to boolean; I get an Invalid Typecast exception in the second line.

I'm using Delphi XE but it is the same result in Delphi Xe6 which leads me to the conclusion: I'm using TValue wrong.

So please what am I doing wrong.


Solution

  • Although you give Boolean as the example in your question, I'm going to assume that you are really interested in the full generality of enumerated types. Otherwise you would just call StrToBool.

    TValue is not designed to perform the conversion that you are attempting. Ultimately, at the low-level, the functions GetEnumValue and GetEnumName in the System.TypInfo unit are the functions that perform these conversions.

    In modern versions of Delphi you can use TRttiEnumerationType to convert from text to an enumerated type value:

    b := TRttiEnumerationType.GetValue<Boolean>(s);
    

    You can move in the other direction like this:

    s := TRttiEnumerationType.GetName<Boolean>(b);
    

    These methods are implemented with calls to GetEnumValue and GetEnumName respectively.

    Older versions of Delphi hide TRttiEnumerationType.GetValue and TRttiEnumerationType.GetName as private methods. If you are using such a version of Delphi then you should use GetEnumName.