Question

I am having an issue where I have a class with a property that is an array. A Load method resizes the array to the number of entries in a file, creates a new Entry class for that file entry, and assigns it to a new element in the property array. However, when I try to use this array outside of my Load method, the array maintains the correct sizing, but all elements are "Empty". Below is basically what I am trying to do. I'm assuming this is a scoping issue with the assignment of the new Entry class, but I am not sure how to correct this being new to VBScript. Below is some quick code to give you an idea of what I'm trying.

Class Entry
    Public Name
End Class

Class Config
    Private theArray()

    Public Sub Load()
        ...
        Do While Not configFile.AtEndOfStream

        if(UBound(theArray) < theCount) Then
            ReDim Preserve theArray(theCount)
        End If

        Set theArray(theCount) = new Entry

        theArray(theCount).Name = "Bobby Joe Sue"
        Wscript.Echo theArray(theCount).Name & " is working"
    End Sub

    Public Function GetList()
        GetList = theArray
    End Function
End Class

Now, if I create an instance of the Config class, call the load method, assign a variable to the GetList result, I can loop through the array and it will be the correct size. HOWEVER, every entry in the array is Empty instead of an instance of the Entry class where I can access Entry.Name. Does anyone have any advice on what to do to fix this?

Was it helpful?

Solution

Your array initialization doesn't work. Change your Class Config like this:

Class Config
  Private theArray

  Private Sub class_initialize()
    theArray = Array()
  End Sub

  '...
End Class

OTHER TIPS

Maybe you miss something.

Set oConfig = New Config
oConfig.Load
aList = oConfig.List
Wscript.Echo "Type: " & TypeName(aList(0))
Wscript.Echo "Name: " & aList(0).Name

'> Bobby Joe Sue is working
'> Type: Entry
'> Name: Bobby Joe Sue

Class Entry
    Public Name
End Class

Class Config
    Private theArray()
    Private theCount

    Public Property Get List()
        List = theArray
    End Property

    Public Sub Load()
        theCount = theCount + 1
        ReDim Preserve theArray(theCount)
        Set theArray(theCount) = new Entry
        theArray(theCount).Name = "Bobby Joe Sue"
        Wscript.Echo theArray(theCount).Name & " is working"
    End Sub

    Private Sub Class_Initialize
        theCount = -1
    End Sub
End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top