İsmail Kocacan
İsmail Kocacan

Reputation: 1234

Get Variable Name Using RTTI

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 ?

Upvotes: 9

Views: 2522

Answers (1)

David Heffernan
David Heffernan

Reputation: 612963

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?

Upvotes: 9

Related Questions