TValue casting to other type

1.7k Views Asked by At

I have

uses
  System.Rtti;

procedure TForm1.BitBtn1Click(Sender: TObject);
var
  _UserString: string;
  _CastedValue: TValue;
  _IntExampleValue: TValue;
  _DateTimeExampleValue: TValue;
begin
  _UserString := '55';
  _IntExampleValue := TValue.From<integer>(-199);

  if not TValue.From(_UserString).TryCast(_IntExampleValue.TypeInfo, _CastedValue)
  then
    ShowMessage('Failed to cast')
  else
    ShowMessage('Casted successfully');

  _UserString := DateTimeToStr(Now);
  _DateTimeExampleValue := TValue.From<TDateTime>(Now);

  if not TValue.From(_UserString).TryCast(_DateTimeExampleValue.TypeInfo, _CastedValue)
  then
    ShowMessage('Failed to cast')
  else
    ShowMessage('Casted successfully');
end;

Both times I get message saying that it failed to cast, but why? I don't see anything wrong.

1

There are 1 best solutions below

0
Remy Lebeau On

TValue is not designed to do those kind of casts. You cannot cast between two incompatible types that the Pascal language itself cannot directly cast between. Just as a String cannot be directly assigned to an Integer or a TDateTime, a TValue<String> cannot be casted to a TValue<Integer> or a TValue<TDateTime>. There is no substitute for using conversion functions like StrToInt() and StrToDateTime().