tonymke
tonymke

Reputation: 862

VB6: How do I properly store class objects in a collection?

I'm looking at a legacy VB6 app, and trying to understand how VB6 Collections work. Using the Collection.Add method, I am finding that the collection just exists of its last added option, repeated. e.g. if I add 1,2,3,4,and 5 to a collection, I will get 5, 5, 5, 5, and 5 back as the collection contents.

In my test case, I have an encapsulation class module, EncapsulationClass.cls that stores some simple strings. Its implementation:

Option Explicit

'ivars
Private pEntityId As String
Private pEntityName As String

'properties
    'pEntityId
    Public Property Get entityId() As String
        Let entityId = pEntityId
    End Property

    Private Property Let entityId(ByVal inEntityId As String)
        Let pEntityId = inEntityId
    End Property


    'pEntityName
    Public Property Get entityName() As String
        Let entityName = pEntityName
    End Property

    Private Property Let entityName(ByVal inEntityName As String)
        Let pEntityName = inEntityName
    End Property


'constructor
    Public Sub init(ByVal inEntityId As String, ByVal inEntityName As String)
        Let entityId = inEntityId
        Let entityName = inEntityName
    End Sub

I want to store several instances of these in an iterable object, so I used a Collection.

In my test case, I have this simple function:

Private Function getACollection() As Collection
    Dim col As New Collection
    Dim data(0 To 5) As String
    data(0) = "zero"
    data(1) = "one"
    data(2) = "two"
    data(3) = "three"
    data(4) = "four"
    data(5) = "five"

    For Each datum In data
        Dim encap As New EncapClass
        encap.init datum, datum & "Name"
        col.Add encap
    Next

    'return
    Set getACollection = col
End Function

This function is then used in the following simple logic:

Private Sub Form_Load()
    Dim col As Collection
    Set col = getACollection()

    For Each i In col
        Debug.Print i.entityId, i.entityName
    Next i
End Sub

I would expect the output to be:

one oneName
two twoName
three threeName
four fourName
five fiveName

However, instead, I simply get a repetition of the last element added, five times.

five fiveName
five fiveName
five fiveName
five fiveName
five fiveName

Is there something I'm missing, syntactically? Looking through various books, collections are appended with the Add method, and work as expected.

Upvotes: 2

Views: 3768

Answers (1)

Alex K.
Alex K.

Reputation: 175886

The lack of a set is effectively reusing the same single instance of encap so changes within the loop modify the single repeated reference already in the collection.

To fix:

 Dim encap As EncapClass

 For Each datum In data
     set encap = New EncapClass
     encap.init datum, datum & "Name"
     col.Add encap
 Next

Upvotes: 6

Related Questions