8

I'm trying to get variable name using RTTI like this.

Here is my test.

type
  TStringHelper = record helper for string
    function Name: string;
  end;

  TMyRecord = record
    Field1:string;
  end;

implementation

{ TStringHelper }
function TStringHelper.Name: string;
var
 context : TRttiContext;
begin
 context := TRttiContext.Create;
 result := context.GetType(@Self).Name; // return empty
 context.Free;
end;

procedure TForm2.FormCreate(Sender: TObject);
var
 r : TMyRecord;
begin
  ShowMessage(r.Field1.Name);
end;

Name of TRttiType returning is empty.

Is there any way get variable name ?

İsmail Kocacan
  • 1,204
  • 13
  • 38

1 Answers1

9

RTTI gives information about types and not about variables. In general there is no way, using RTTI, given the address of a variable, to find its name.

Not only does RTTI not help, but what you are attempting, as a method of a string object, is not actually possible. Imagine a scenario where you have two variables referring to the same object.

S := 'foo';
T := S;

What is the name of the single string object here. Is it S or is it T?

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thank you very much for explain. It would have been nice if RTVI(Run Time Variable Information) had. :) – İsmail Kocacan Nov 02 '16 at 08:09
  • 5
    Nothing "runtime" needed here. The compiler would just need an intrinsic that turns a symbol into a string at compile time. Just like the nameof function in C# 6. - vote for it: https://quality.embarcadero.com/browse/RSP-13290 – Stefan Glienke Nov 02 '16 at 11:24