1. Home
  2. Computing & Technology
  3. Delphi Programming

Class Helper for Delphi's TStrings: Implemented Add(Variant)
Implementing ListBox1.Add(5) and ListBox1.Add(True)

By , About.com Guide

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;

Delphi tips navigator:
» File Size - Get the Size of a File in Bytes using Delphi
« Overloading Delphi's ShowMessage to accept Integer, Boolean, Float, Currency ...

Explore Delphi Programming
About.com Special Features

Reader's Choice Award Winners

What are the best instant messengers, apps, editors and more? You told us, for our 2010 technology awards program. More >

iPad Central

Is Apple's new tablet computer impractical, a must-have -- or both? We'll help you figure it out. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2008 Tips
  7. Class Helper for Delphi's TStrings: Implemented Add(Variant)

©2010 About.com, a part of The New York Times Company.

All rights reserved.