5

Can someone explain to me if this is possible, or I'm completely missunderstanding this Delphi feature.

Let's say I have a class, I create a few of them, and then add them to an ObjectList. Normally I do it like this:

Type TMyClass = class(TObject)
  stuff: string;
..
end;

Var things: TObjectList;

things := TObjectList.Create;
things.Add(TMyClass.Create);

// now I want to access stuff, so I need to typecast the class
TMyClass(things[0]).stuff..

So now my question, is it possible to declare the list in a way where I could just do like.. things[0].stuff and still have access to the the usual TObjectList features like .sort .indexof etc..? (without making a special class for this to simulate the objectlist)

hikari
  • 3,174
  • 27
  • 64

1 Answers1

7

You are using the TObjectList from System.Contnrs, which manages a list of pointers.

You want TObjectList from System.Generics.Collections. I know, using the same name can be a little confusing.

Type TMyClass = class(TObject)
  stuff: string;
..
end;

Var things: TObjectList<TMyCLass>;

things := TObjectList<TMyCLass>.Create;
things.Add(TMyClass.Create);

things[0].stuff..
Bruce McGee
  • 14,728
  • 6
  • 53
  • 68
  • Thanks, that's very useful. One last thing, can you give me an example of an IComparer function to use with this different type of objectlist? the usual functions don't work with this. (for .sort) – hikari Oct 27 '14 at 01:07
  • 1
    @hikari http://stackoverflow.com/questions/13252169/how-do-i-sort-a-generic-list-using-a-custom-comparer/13252367#13252367 – David Heffernan Oct 27 '14 at 07:21