Why variables are declared as TStrings and created as TStringList?
eg: the var sl is declared as TStrings but created as TStringList
var
sl : TStrings;
begin
sl := TStringList.Create;
// add string values...
sl.Add( 'Delphi' );
sl.Add( '2.01' );
// get string value using its index
// sl.Strings( 0 ) will return
// 'Delphi'
MessageDlg(
sl.Strings[ 0 ],
mtInformation, [mbOk], 0 );
sl.Free;
end;
To my mind that is rather pointless albeit completely harmless. You could perfectly well declare
slto beTStringListand 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
slis always assigned aTStringListinstance and so there’s nothing to be gained from declaringslto have the base class type ofTStrings. However, if you had code that assigned a variety of different types ofTStringsdescendants to the variable, then it would make sense to declare it asTStrings.The situations when you might declare a variable to be of type
TStringswould 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 aTStringssince then any descendant could be passed to it. Here’s a simple example:Clearly this is of much greater utility when the parameter is declared to be
TStringsrather thanTStringList.However, the code in the question is not of this nature and I believe that it would be ever so mildly improved if
slwas declared to be of typeTStringList.