Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can TBytes, TByteDynArray, Array of Bytes be safely typecasted to each other?

Tags:

casting

delphi

Since TBytes, TByteDynArray, and array of Bytes are all dynamic arrays of bytes, can typed variables be safely typecasted to each other? (If I have a variable of TBytes can I simply typecast to TByteDynArray when using a method that defines parameters as TByteDynArray and vice-versa?)

like image 736
Darian Miller Avatar asked Dec 07 '11 18:12

Darian Miller


1 Answers

Such typecasts are perfectly safe in all the Delphi implementations that I have ever encountered.

However, reinterpretation typecasts like this remove type checking, there is always a risk that future changes to the source code can result in hard to trace errors. I would always try to avoid casting if possible. For example, the very simplest thing you can do is to avoid using array of Byte as a type in your code and switch to TBytes.

If you must cast then wrap it up in a function to mitigate the risks I describe above.

function Bytes(const B: TByteDynArray): TBytes;
begin
  Result := TBytes(B);
end;
like image 100
David Heffernan Avatar answered Oct 21 '22 13:10

David Heffernan