Board index » delphi » q: passing string element of stringlist by ref

q: passing string element of stringlist by ref

How do I pass a string element of a stringlist as a reference? See
example of what I'd like below:

procedure DoSomething(var AString: string);
begin
  AString := 'do something';
end;

procedure Main;
var
  StringList: TStringList;
begin
  StringList := TStringList.Create;

  try
    StringList.Add('this is a string');
    DoSomething(StringList[0]);
    ShowMessage(StringList[0]); // would like it to display 'do
something'
  finally
    StringList.Free;
  end;
end;

 

Re:q: passing string element of stringlist by ref


Quote
Holger Danske wrote:
> How do I pass a string element of a stringlist as a reference? See
> example of what I'd like below:

You don't. To pass something by reference, you need to be able to take
the address of it. You can't take the address of a function result, and
the value of the TStrings.Strings property is determined by a function.
(Actually, can't send any properties by reference, even if their values
aren't determined by functions.)

Quote
> procedure DoSomething(var AString: string);
> begin
>   AString := 'do something';
> end;

Change that to

function DoSomething: string;
begin
   Result := 'do something';
end;

Or, if the result of the function depends on the input, then do this:

function DoSomething(const AString: string): string;
begin
   Result := 'do something';
end;

Quote
>     DoSomething(StringList[0]);

StringList[0] := DoSomething(StringList[0]);

Don't be worried about a big change in performance. There really
shouldn't be much of a change. Either way, there'd still be the two
function calls to access the Strings property, and there would still be
the string-clearing and string-assigning functions. I'd say there's no
significant difference.

--
Rob

Re:q: passing string element of stringlist by ref


Re:q: passing string element of stringlist by ref


Quote
"Holger Danske" <n...@mail.thx> wrote in message

news:MPG.1930f6597ff84b3898968c@news.inet.tele.dk...

Quote
> How do I pass a string element of a stringlist as a reference? See
> example of what I'd like below:

As Rob Kennedy suggested, you can't.

Quote

> procedure DoSomething(var AString: string);
> begin
>   AString := 'do something';
> end;

But you can let DoSomething modify a particular entry in a string list

procedure DoSomething (aList : tStrings; anIndex : integer);

begin
. . .
aList [anIndex] := 'do something';
. . .
end;

Other Threads