How can I create a list that can hold objects of different types?

delphi

Solution

Delphi does not support lists of heterogeneous types. You have to be able to represent all the potential values with a single type. One way to do that is by joining all the different types into a single discriminated union:

type
  TPointUnion = record
    case NumDimensions: Integer of
      2: (p2: TPoint);
      3: (p3: TPoint3D);
  end;

Then you can declare a list of that type:

var
  List: TList<TPointUnion>;

You can add values of type `TPointUnion` to the list. To construct a value of that type, simply assign the `NumDimensions` field, and then assign the corresponding `p2` or `p3` field. When reading such a value, check the `NumDimensions` field to discover which point field holds a valid value. In practice, `p2` is always safe to use since its fields overlap with the corresponding fields of `p3`.

Problem

I am currently using a generic list typed like this: ``` List: TList<TPoint>; ``` I would like for `List` to be able to hold, as an alternative, points with three coordinates: ``` type TPoint3D = record x, y, z: Integer; end; ``` I'd like to declare something like this: ``` List: TList<TCanBeEitherTPointOrTPoint3D>; ``` Naturally this won't work, but I don't know what will work!

Original source