Delphi: TArray of T versus TArray; a function can return the latter, but not the former
Posted by jpluimers on 2021/07/05
I wish I had blogged about this a lot sooner, as then far less people would use var aFoo: array of TFoo
as method parameters for results that are just out
parameters and could be a function result.
You cannot have array of TFoo
as function result, but you can have TArray<TFoo>
. The former would be an open array, the latter is a proper array type.
I see many people use var aFoo: array of TFoo
with all sorts of SetLength
calls before calling and inside a method where a function returning a TArray<TFoo>
would be far more appropriate, both in the sense of readability and maintainability.
–jeroen
Remy Lebeau said
“You cannot have array of TFoo as function result … [that] would be an open array” – it is not an open array when used as a function result, only when used directly in a parameter declaration. Any use of “array of …” outside of a parameter declaration is a dynamic array, not an open array. Open Arrays are a special use-case of “array of …” only in parameters.
Stefan Glienke said
var is not about returning that array but passing it to the method allowing it to be modified – common signature in sorting for example. Changing the parameter to
TArray<T>
instead of using the open array argument breaks compatibility.