Why are TGeneric and TGeneric incompatible types?

TDataProviderThread is a descendant of TThreadBase, but TThreadBaseList<TDataProviderThread> is not a descendant of TThreadBaseList<TThreadBase>. That’s not inheritance, it’s called covariance, and though it seems intuitively like the same thing, it isn’t and it has to be supported separately. At the moment, Delphi doesn’t support it, though hopefully it will in a future release.

Here’s the basic reason for the covariance problem: If the function you pass it to is expecting a list of TThreadBase objects, and you pass it a list of TDataProviderThread objects, there’s nothing to keep it from calling .Add and sticking some other TThreadBase object into the list that’s not a TDataProviderThread, and now you’ve got all sorts of ugly problems. You need special tricks from the compiler to make sure this can’t happen, otherwise you lose your type safety.

EDIT: Here’s a possible solution for you: Make MakeAllThreadsActive into a generic method, like this:

procedure MakeAllThreadsActive<T: TThreadBase>(aThreads: TThreadBaseList<T>);

Or you could do what Uwe Raabe suggested. Either one will work.

Leave a Comment