Title: Class Helper for Delphi's TStrings: Implemented Add(Variant)
Tip submitted by Jens Borrisholt
In Delphi, the TStrings is the base class for objects that represent a list of strings. Examples include Lines property of a TMemo, Items property of a TListBox or TComboBox, etc.
To add strings to the list you use the Add method which accepts a string parameter.
When you need to add integer values, boolean values or any other non-string values to the list you need to use some of the RTL's conversion routines (from int to string for example).
Wouldn't it be better if you can simply say "Add(2008)" or "Add(True)"?
Class Helper for TStrings - Add method to accept Variant types
Here's the implementation of the TStringsHelper unit to extend the TStrings class's Add method:
unit TStringsHelperU;
//class helper for TStrings
//delphi.about.com
interface
uses Classes;
type
TStringsHelper = class helper for TStrings
public
function Add(const V: Variant): Integer; overload;
function Add(const Args: array of Variant): Integer; overload;
end;
implementation
uses Variants;
function TStringsHelper.Add(const Args: array of variant): Integer;
var
tmp: string;
cnt: Integer;
begin
tmp := '';
for cnt := Low(Args) to High(Args) do
tmp := tmp + VarToStr(Args[cnt]) ;
result := Add(tmp) ;
end;
function TStringsHelper.Add(const V: Variant): Integer;
begin
Result := Add([V]) ;
end;
end.
An example of usage:
with ListBox1.Items do
begin
Add('delphi.about.com') ;
Add(2008) ;
Add(true) ;
Add(['Only ', 1, true, ' line']) ;
end;