On Sat, 15 Oct 2022, Hairy Pixels via fpc-pascal wrote:
Another question I just ran in to. Why isn’t "array of TMyClass” compatible
with “array of TObject” open array? TMyClass is a descendant of TObject and dynamic
arrays are compatible with open arrays right?
======================
type
TMyClass = class
end;
procedure MyProcedure(values: array of TObject);
begin
end;
var
myArray: array of TMyClass;
begin
MyProcedure(myArray); // error: Incompatible type for arg no. 1: Got "{Dynamic} Array Of
TMyClass", expected "{Open} Array Of TObject"
Rougly said:
Arrays are considered equal if the element type is equal.
And equal does not mean 'inherits from'.
One reason we do not allow descendents is that if you have a var array, the
returned value may contain classes of a type that the caller does not expect.
(This is the same reason why (var value: TObject) requires an exact match in
type)
But a case could be made to allow it in case the parameter is passed by value.
You can force it with a typecast:
Type
TObjectArray = Array of Object;
var
myArray: array of TMyClass;
begin
MyProcedure(TObjectArray(myArray));
end.
But then you're on you own, as you are deliberately bypassing the compiler's
typechecking (as is the case with all typecasts...).
Michael.
_______________________________________________
fpc-pascal maillist - fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal