Why variables are declared as TStrings
and created as TStringList
?
eg: the var sl
is declared as TStrings
but created
To my mind that is rather pointless albeit completely harmless. You could perfectly well declare sl
to be TStringList
and I would always do it that way. For a reader of the code it makes the list of local variables easier to understand.
In this code sl
is always assigned a TStringList
instance and so there's nothing to be gained from declaring sl
to have the base class type of TStrings
. However, if you had code that assigned a variety of different types of TStrings
descendants to the variable, then it would make sense to declare it as TStrings
.
The situations when you might declare a variable to be of type TStrings
would typically be when the code was not explicitly creating the instance. For example a utility method that received a string list as a parameter would be more useful if it accepted a TStrings
since then any descendant could be passed to it. Here's a simple example:
procedure PrintToStdOut(Strings: TStrings);
var
Item: string;
begin
for Item in Strings do
Writeln(Item);
end;
Clearly this is of much greater utility when the parameter is declared to be TStrings
rather than TStringList
.
However, the code in the question is not of this nature and I believe that it would be ever so mildly improved if sl
was declared to be of type TStringList
.