Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 671
Jens Borrisholt Avatar asked Jan 13 '15 08:01

Jens Borrisholt


2 Answers

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.

like image 135
David Heffernan Avatar answered Sep 19 '22 00:09

David Heffernan


TValue is not meant to convert types that are not assignment compatible. It was designed to hold values while transporting them in the RTTI and to respect the assignment rules of Delphi.

Only ToString can output the value in some string representation but a type that you cannot simply assign a string to will also fail when doing that with TValue.

TValue is not a Variant.

If you want to convert a string to boolean and back then use StrToBool and BoolToStr.

like image 36
Stefan Glienke Avatar answered Sep 20 '22 00:09

Stefan Glienke