TListRemove (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code adds a new object to a list in a list object and then removes it.

Code

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  TMyClass = class
    MyString: string;
    constructor Create(S: string);
  end;

var
  Form1: TForm1;
  MyList: TList;

implementation

{$R *.dfm}

constructor TMyClass.Create(S: string);
begin
  MyString := S;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  MyObject: TMyClass;
begin
  MessageDlg('The list starts with ' + IntToStr(MyList.Count) + ' objects',
    mtInformation, [mbOk], 0);
  try
    MyObject := TMyClass.Create('Semper Fidelis!');  { create a class instance }
    try
      MyList.Add(MyObject);      { Add instance to the list. }
      MessageDlg('The list has ' + IntToStr(MyList.Count) + ' objects',
                 mtInformation, [mbOk], 0);
      MyList.Remove(MyObject);
      MessageDlg('The list has ' + IntToStr(MyList.Count) + ' objects', 
                 mtInformation, [mbOk], 0);
    finally
      MyObject.Free;
    end;                  { Do not forget to clean up. }
  finally
    MyList.Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  I: Integer;
begin
  MyList := TList.Create;              { Create a list. }
  MyList.Add(PChar('A string')); { Add a string. }
  MyList.Add(PChar('')); { Add an empty string. }
  MyList.Add(PChar('A third string')); { Add a string. }
  MyList.Add(nil);              { Add nil. }
  MyList.Add(PChar('A fifth string')); { Add a string. }
  MyList.Add(PChar('')); { Add another empty string. }
  MyList.Add(PChar('A seventh string')); { Add a string. }
end;

Uses