Home > Blockchain >  How is an array with a length declared within a class? [Visual Basic]
How is an array with a length declared within a class? [Visual Basic]

Time:01-20

I want to declare an array with a set length as a Public Property within a class, and fill the array with zeroes so that squares(0) = squares(5) = squares(42) = 0, etc.

What I tried:

Public Class Board     
    Public Property squares(width*height) As Integer 
End Class

What I expected:

squares = {0,0,0,0,0,0,0,0}

What actually happened:

Error BC36759: Auto-implemented properties cannot have parameters

CodePudding user response:

Public Class Board
    Public Property squares As Integer()

    Sub New(ArraySize As Integer)
        ReDim squares(ArraySize)
    End Sub

End Class

When you create the class, you create it like:

MyBoard = New Board(64)

CodePudding user response:

Here's a variation, if your size is hard-coded:

Public Class Board

    Private width As Integer = 5
    Private height As Integer = 10
    Private _squares(width * height) As Integer

    Public ReadOnly Property squares As Integer()
        Get
            Return _squares
        End Get
    End Property

End Class

CodePudding user response:

Another variation, maintaining the auto-property and using a valid private field name:

Public Class Board
    Private Const width As Integer = 5
    Private Const height As Integer = 10

    Private privateSquares(width * height) As Integer
    Public Property squares() As Integer() = privateSquares
End Class

Note that you can't name the new private field "_squares" because that conflicts with a hidden field that VB uses.

CodePudding user response:

Or

Public Class Board

    Private _board() As Integer = New Integer() {}
    Public ReadOnly Property Squares() As Integer()
        Get
            Return Me._board
        End Get
    End Property

    Public Sub New(width As Integer, height As Integer)
        Array.Resize(Me._board, width * height)
    End Sub
End Class
  • Related