I'm trying to create a class that uses an array as a property, but I can't get it to work. I've tried doing this like 3 completely different ways and they all yield the same error. The first line of code generating the error is

.question(0) = "abc"

. Please help.

Module mod1
    Class test
        Public questioncount As Byte
        Private mstrQuestion As String()
        Public Property question() As String()
            Get
                Return mstrQuestion
            End Get
            Set(ByVal value As String())
                mstrQuestion = value
            End Set
        End Property
    End Class
    Public genericTest As New test
    Public Sub setTests()
        With genericTest
            .questioncount = 3
            .question(0) = "abc"
            .question(1) = "abcd"
            .question(3) = "abcde"
        End With
    End Sub

End Module

You have to initialize the array before using it. A list of string would be easier.

Class test
        Private mstrQuestion As List(Of String)

        ReadOnly Property QuestionCount() As Integer
            Get
                Return mstrQuestion.Count
            End Get
        End Property

        ReadOnly Public Property Questions() As List(Of String)
            Get
                Return mstrQuestion
            End Get
        End Property

        Sub New()
            mstrQuestion = New List(Of String)
        End Sub

    End Class

    Public genericTest As New test

    Public Sub setTests()
        genericTest.Questions.Add("Abc")
        genericTest.Questions.Add("Abd")
    End Sub

    Public Sub GetTests()
        'Iterate them
        For Each Question As String In genericTest.Questions

        Next
    End Sub

Don't forget to mark your threads as solved when they are solved <edit>
if you wanted to use the array then you would need to call redim preserve genericTest.questions(genericTest.questions.length) every time you wanted to add to it. Thats why a list is better in this case. You can just call add.

Edited 5 Years Ago by Unhnd_Exception: n/a

This article has been dead for over six months. Start a new discussion instead.