1

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.

Mike Torrettinni
  • 1,816
  • 2
  • 17
  • 47
Edijs Kolesnikovičs
  • 1,627
  • 3
  • 18
  • 34

1 Answers1

0

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().

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770