Post

VB10 vs VB6: Dynamic Arrays Usage In Structures

This is part of series of posts categorized under VB10 vs VB6.

“Dynamic arrays are not allowed within structures (UDTs)”

I’m kind of scratching my head by this statement as I’m not entirely sure what he means by “dynamic arrays”. I will assume that he means:

1
2
3
Structure SomeType
  Public SomeArray() As Integer
End Structure 

The above is an array of integers that has no defined indexer. Additionally, the above code does not present any sort of error within Visual Studio.

1
2
Dim s As SomeType 
Redim s(20) 

Again, the above code appears to be syntactically correct within Visual Studio. So we created a structure, defined an array and re-dimensioned the array.

However, with the advent of Generics and the flexibility that they bring to the table, I’d modify the structure so that it utilizes a Generic List as follows:

1
Public SomeArray() As List(Of Integer)

You would, however, have to initialize the array as it would begin “life” as Nothing. To do this:

1
2
Dim s As SomeType 
s.SomeArray = New List(Of Integer)  

From here, you could use the Add, Insert, Remove, etc. available on the Generic List to truly provide a “dynamic array” that is far above and beyond what was available with VB6 “native” arrays.

Verdict

So unless I’m misinterpreting the statement, VB does fully support “dynamic arrays” in user defined types (Structures). With that said, I have to hand this one to VB10.

Update(s)

Well, technically not an update as it was in an email I got before I finished writing this entry, Bill McCarthy (MVP) points out that this “issue” may be related to usage of dynamic arrays in structures with regards to Win32 API and the “default marshalling” done. This is a very good point and one that can be answered by pointing to the previous entry where I point out that the .NET Interop story is much better than the VB6 counterpart. With that said, I’d like to point you to the complete list of ways that the .NET Interop mechanism can do using the MarshalAs attribute. See MSDN Unmanaged Type Enum. As you can see, you have a plethora of choices specifically regarding arrays. Thanks Bill for bringing this to my attention.

This post is licensed under CC BY 4.0 by the author.