A Better TObjectList

There have been several times in my Delphi programming ventures that I needed a good object container.  One that will handle any type of object that you throw into it.  I also wanted this container to be thread safe, as well as be protective of itself.  I have used TObjectList before with less than stellar results. I decided there has to be a better way.  The TObjectList container just didn’t cut it. One of the  ExpertsExchange gurus posted a chunk of code that, for the most part, worked very well, but had a few problems.  I took their code and tweaked it a bit, added a good bit of additional functionality, fixed a memory leak in it, and generally cleaned it up.  The final work is a thread safe class called TObjectContainer.  After extensive testing,  I think this code snippet is a final work so here are the results.


TObjectContainer Code:


As you can see, its a very simple implementation of a much needed functionality.  I use it heavily and it just works.  Since no good code snippet should ever be posted without an example using it, I posted one below.


Here is a quick example I wrote using the above class:


I am always interested in improving the snippets posted on this site.  If you have any suggestion and/or improvements to add to the above class, please post in the comments below. Thanks!

  • Facebook
  • Add to favorites
  • Email
  • RSS
  • PDF
  • Print

2 Responses to “A Better TObjectList”

  1. Wolfgang Prinzjakowitsch says:

    i think that you have to check the validity this way:

    function TObjectContainer.DeleteByIndex(Index: Integer): Integer;
    result := 0;

    if FList.Count > index then

    • Chris McClenny says:

      Hi Wolfgang,
      Thanks for pointing that out. I missed that check. I will update the code to reflect that.

      Thanks again!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">