Delphi Programming

  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 Zarko Gajic, About.com

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 ...

More Delphi Programming Quick Tips
Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Delphi Programming

  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)

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

All rights reserved.