tags:

views:

71

answers:

3

Hi guys,

I'm trying to ReDim a member object array from a different class. For example:

Class1.cls

Dim mStuffArray() As New clsStuff

Property Get StuffArray() As clsStuff()
    StuffArray = mStuffArray
End Property

Class2.cls

Private Sub Foo(ByRef pClass1 As Class1)
    Dim tStuffArray() As clsStuff

    tStuffArray = pClass1.StuffArray
    ReDim tStuffArray(1 To 2)
End Private

The problem here is that Foo doesn't seem to be ReDim'ing the member mStuffArray in Class1. Any idea what I'm doing wrong? Forgive me if my VB6 looks odd or the naming conventions aren't standard, I had to dive into some old legacy code and am new to VB6

Dave

+1  A: 

I've never looked into VB6, but if I were to take a guess, I think when you use ReDim, it creates a copy of the existing Array and changes tStuffArray to point to the new copy. However, pClass1.mStuffArray still references the old array.

The documentation for ReDim states that "ReDim creates a new array, copying all the elements from the existing array"

I would recommend adding a method to to Class1 that performs ReDim on the private mStuffArray variable.

Dim mStuffArray() As New clsStuff

Property Get StuffArray() As clsStuff()
    StuffArray = mStuffArray
End Property

Sub Foo()
     ReDim mStuffArray(1 To 2)
End Sub

Hopefully this works. As I said, I'm not a VB6 programmer, so I may be off on this.

regex
Ah interesting. That's a plausible reason why my code doesn't work. Can anyone confirm that behavior of ReDim? Or possible any other elegant methods of handling my case?
Perishable Dave
I've settled on adding a Let property and calling the let right after I redim the array. But thanks, your information on ReDim was helpful in understanding how it works.
Perishable Dave
You've linked to the VB.Net documentation not the VB6 docs
MarkJ
@MarkJ, Good call... I'm thinking I may have been way off on my answer. As I stated: I'm not 100% on VB6, but I was hoping I could at the least point Dave in the right direction. For now I'll upvote your answer, but I'm hoping Dave will come back and mark you as the answer so that you get the credit.
regex
+3  A: 

Redim doesn't make a copy of the array.

I think it's more likely that 4eturning the array from a property get creates a copy. The docs aren't very clear. http://msdn.microsoft.com/en-us/library/aa261343(VS.60).aspx

It would be simpler to use a Public member variable. And why not use a Collection rather than an array?

MarkJ
Yes a "copy" (value) is returned, not a reference to the original.
Bob Riemersma
Thanks for the help MarkJ and Regex. It's been quite, well, interesting going back to VB 6 from modern languages.
Perishable Dave
A: 

You might also want to consider the Dictionary object.

BobRodes