I’m migrating a legacy Delphi application to Delphi-XE2, and I’m wondering if there’s a good reason to replace the arrays defined as Array of MyType to TArray<MyType>. So the question is what are the pros and cons of TArray<T> usage instead of Array of MyType?
I’m migrating a legacy Delphi application to Delphi-XE2, and I’m wondering if there’s a
Share
The main advantage is less onerous type identity rules. Consider:
These two variables are not assignment compatible. It is a compiler error to write:
On the other hand if you use the generic syntax:
then these two variables are assignment compatible.
Sure, you can write
But all parties need to agree on the same type. It’s fine if all code is in your control, but when using code from a variety of sources, the advent of generic dynamic arrays makes a huge difference.
The other advantage that springs to mind, in similar vein, is that you can readily use the generic array type as the return type of a generic method.
Without the generic array you are compelled to declare a type of this form:
in your generic class, which is rather messy. And if you are writing a generic method in a non-generic class, then you’ve no way to make that declaration. Again the generic array solves the problem.
This all follows on from type compatibility rules described in the documentation like this: