I’m not sure if this is possible in Delphi. I’ve looked around and can’t seem to find an answer (Example or inidaction that it’s not possible):
I have a generic list class, and I want to create an instance of the generic type. For example:
type
TTypeA = class(TObject);
procedure Test;
var
MyList: TobjectList<TTypeA>;
NewListObject: TTypeA;
begin
MyList := TObjectList<TTypeA>.Create;
NewListObject := MyList.xxx //what to put on the xxx
end;
Is it possible to create a function xxx that creates a new object of the type TTypeA?
@jeroen: thanks for the answer below. However, I forgot an important detail in my question:
I would like this code to work for any other type as well, so without prior knowledge about the type T for TObjectList. I might create the following lists:
MyList: TObjectList<TCar>;
MyList: TObjectList<TBike>;
Without knowing if MyList contains TCar or TBike (both derived from the same base class and equal constructors) I want to add a new item to MyList.
And with the suggestion from Uwe Raabe I run into the next problem:
I modified my class to
TMyObjectList<T:class, constructor> = class(TMyBaseObjectList<T>)
where TMyBaseObjectList is defined as
TMyBaseObjectList<T:TMyBaseObject> = class(TObjectList)
Now I get an error:
Type parameter ‘T’ is not compatible with type ‘T:TMyBaseObject’
As you know the type, why don’t you just write
It would be the natural way to do here. (I’m just notified by Jeroen’s similar answer)
If you want the container create the object, you have to make a descendant class that knows a little bit more about the generic type to create an instance. The constructor constraint might help here.
Note: This will only work when the actual type has a parameterless constructor named Create.
Update: This will help