Arrays in Dictionary

I want to store arrays of objects into a dictionary

[code]Dim d as New Dictionary

d.Value(“Hello”)=Array(a, b, c)
d.Value(“Godbye”)=Array(d, e, f)

a, b c, d, e, f are objects of myClass.

But how can I use array functions with the dictionary? For example d.Value(“Hello”).Append does not work, because Value() returns a variant, and not an array. I thought about a helper function to access the array:

[code]Public Function GetArray(Key As String) as myClass()
Dim c() As myClass

If Not d.HasKey(Key) Then
End If

Return d(Key)
End Function

Will that work? I thought about things like:

GetArray(Key).Append a

And is this efficient? The arrays will have many objects and will be accessed in drawing methods, so it has to be fast. And for that it would be great if GetArray() returns a reference of the array in the dictionary and not a new created array.

I don’t know if this function will return the array ByRef of ByVal. And if its ByVal, how to force the return value being ByRef. Can you help me?

For the sake of efficiency, I’d do it like this:

d.Value( "key" ) = myArr

// Later

dim myArr() as MyObject = d.Value( "key" )
myArr.Append x
myArr.Remove y
// etc

// Since the array is already stored in the Dictionary
// there is no need to store it again
1 Like

@Yves Pellot
An array stored in a Dictionary is actually a reference to the array (or any other Object). It does not matter whether you get the reference from the Dictionary or you have a copy of it somewhere: any modification will be seen by both.

And as a rule of thumb, for things other than numerical values, only Structures are passed ByVal in an OOP environment

This has caused much pain for me over the years; Unless the data is a core data type, you really need to know what it is before you can decode it.

You can use variant.arrayElementType to figure out standard data types, but objects simply return “typeObject” and from there it’s virtually impossible.

If you have only certain object types, that need to be accessed directly within arrays stored in variants (that’s what a Value in a Dictionary is), you can build your own accessor function like the built-In Variant.StringValue.

[code]Public Function myClassArrayValue(Extends v as Variant) as myClass()
Dim result() As myClass

If v.IsArray And v.ArrayElementType = Variant.TypeObject Then
//you could check for UBound > -1 and check the first or all elements with IsA myClass but just assigning would throw an error anyhow
result = v
Raise New IllegalCastException
End If

Return result
End Function

I use that a lot for Arrays of Pair and even to ease access to instristic Types like Integer:

i = d.Value("whatever").IntegerArrayValue(5)

or in your case: