I have the following code:
TBase = class
end;
TBaseArray = array of TBase;
TDerived = class(TBase)
end;
TDerivedArray = array of TDerived;
procedure DoSomething(const BaseArray: TBaseArray);
function DerivedArrayToBaseArray(const DerivedArray: TDerivedArray): TBaseArray;
procedure Test;
var
BaseArray: TBaseArray;
DerivedArray: TDerivedArray;
implementation
procedure DoSomething(const BaseArray: TBaseArray);
begin
end;
function DerivedArrayToBaseArray(const DerivedArray: TDerivedArray): TBaseArray;
begin
SetLength(Result, Length(DerivedArray));
for var i := Low(DerivedArray) to High(DerivedArray) do
Result[i] := DerivedArray[i] as TBase;
end;
procedure Test;
begin
DoSomething(BaseArray);
DoSomething(DerivedArray); { Error E2010 Incompatible types: 'TBaseArray' and 'TDerivedArray' }
DoSomething(TBaseArray(DerivedArray)); { Works }
DoSomething(DerivedArrayToBaseArray(DerivedArray)); { Works }
end;
DoSomething(DerivedArray)
expectably does not compile with error E2010 Incompatible types.
DoSomething(TBaseArray(DerivedArray))
compiles and seems to work correctly. I am just wondering, if this hard typecast can cause problems in special situations?
DoSomething(DerivedArrayToBaseArray(DerivedArray))
is a safe possibility and works. However, it is relatively slow and gets tedious in the case of multiple derived classes.
Can I generally use the hard typecast TBaseArray(DerivedArray)
, or should I better use something more safe?
2