Any efficient way to convert TArray<string> to TStringDynArray? Any efficient way to convert TArray<string> to TStringDynArray? arrays arrays

Any efficient way to convert TArray<string> to TStringDynArray?


The best solution is to convert all dynamic arrays in your codebase to be TArray<T>. This is best because generic types have much less stringent type compatibility rules. So I suggest that you consider taking this step across your codebase.

However, that's only viable in the code that you control. When interfacing with code and libraries that you cannot modify you have a problem.

At the root of all this, all these types are dynamic arrays and share a single, common, implementation. This means that the blockage is at the language level rather than implementation. So a cast can be used, safely, to make the compiler accept you assignments.

var  DynArr: TStringDynArray;  GenericArr: TArray<string>;....DynArr := TStringDynArray(GenericArr);GenericArr := TArray<string>(DynArr);

You can use these casts in function call arguments.

Because you are suppressing type checking, you really don't want to scatter these casts all over your code. Centralise them into helper functions. For instance:

function StringDynArray(const arr: TArray<string>): TStringDynArray;begin  Result := TStringDynArray(arr);end;

One final comment: this related question may be of interest: Is it safe to type-cast TArray<X> to array of X?