Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2022-10

Open array compatibility

3 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Hairy Pixels

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"

Regards,
Ryan Joseph

Reply by email

Michael Van Canneyt
to Hairy Pixels
Hairy Pixels wrote 16 lines
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.

Reply by email

Hairy Pixels
to Michael Van Canneyt
Show quoted text 6 lines
On Oct 15, 2022, at 3:58 PM, Michael Van Canneyt wrote: 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)

Ah ok, I guess there would need to be an “array of class” like it used with generic param constraints i.e. <T: class>. I’m trying to do some tricks with overloading which is why I ask.

Regards,
Ryan Joseph

Reply by email