This has been asked several different ways already - but I haven\'t found my answer yet.
Can someone clarify a few things for me please. Using : Delphi XE2
I
Delphi generics do not support covariance and contravariance so what you are attempting to do is not possible with the language's current syntax. I suggest you have a read of the following blog articles that cover the matter in more detail.
Fundamentally what you are attempting to do is this:
type
TBase = class;
TDerived = class(TBase);
TBaseList = TList<TBase>;
TDerivedList = TList<TDerived>;
var
BaseList: TBaseList;
DerivedList: TDerivedList;
...
BaseList := TDerivedList;//does not compile
The designers have not stopped you doing this out of spite. There is a good reason. Consider the following standard example:
type
TAnimal = class;
TCat = class(TAnimal);
TPenguin = class(TAnimal);
var
AnimalList: TList<TAnimal>;
CatList: TList<TCat>;
Penguin: TPenguin;
...
AnimalList := CatList;//does not compile because...
AnimalList.Add(Penguin);//...of the danger of this
Whilst it is reasonable to add a TPenguin to a TList<TAnimal>, the actual list that AnimalList refers to is a TList<TCat> and a penguin is not a cat.
And, if you want to think of it in the context of your example hierarchy, here's an illustration of code that justifies the language design.
aList := aCustomerList;//does not compile
aList.Add(aCustomPerson);
//this would add a TCustomPerson instance to a list containing
//TCustomer instances, but a TCustomPerson is not a TCustomer