BerndL
BerndL

Reputation: 3

Tstringlist vs. Tstrings in a procedure call

I want to use a Delphi library from a friend, this lib contains several procedures like below with the tstrings class.

AStringsprocedure (param_lines : TStrings;  .....  others stuff) 
begin 
     ///  add some add lines eg. to a memo or ....
     param_lines.add ('some text'); 
     .....
end;

in the reference code these functions a called like

 AStringsprocedure (Outmemo.Lines, .... );

passing vcl gui components.

I want to use these functions but I need to pass a TStringlist class instead. How to use this functions with a TStringlist, any cast or ... trick?

Upvotes: 0

Views: 412

Answers (1)

Jerry Dodge
Jerry Dodge

Reputation: 27266

In Delphi, TStringList is defined as so:

TStringList = class(TStrings)

Meaning TStringList already is a TStrings. Components/controls expose such properties as a TStrings which is abstract, no actual implementation inside. TStringList on the other hand contains the actual implementation. Internally, they use TStringList to contain the actual data, but make it available via TStrings. For example, in the TStrings, abstract methods only describe the signatures...

procedure Insert(Index: Integer; const S: string); virtual; abstract;

And then TStringList actually implements them...

procedure Insert(Index: Integer; const S: string); override;

So long story short, you don't need to do any casting/converting - you can just implicitly pass your TStringList as is.


Bonus

Sometimes, you might see something like this...

var
  L: TStrings;
begin
  L:= TStringList.Create;
  ...
end;

TStrings, being the base class of TStringList, is only a placeholder for whatever implementation you might have. But when you actually create it, you tell it what implementation to use. In most cases, TStringList is used. But every now and then, you might find another class which inherits from TStrings and implements it. You could even write your own implementation too if you wanted to, and override the abstract methods to your needs.

Upvotes: 3

Related Questions