Search code examples
vb.netstructure

How to Assign A Structure Type In Declaration Moment?


I declared a variable whose type is structure i did , but i can't assign it

Structure SHAPE
    Dim x as integer
    Dim y as integer
End Structure

Dim Shape1 As SHAPE = (15, 20) ' << The Problem is here

Public Sub test()
    Label1.Text = Shape1.x
End Sub

Solution

  • Structures don't magically understand whatever way you choose you try to get data into them. Like any type, if you want to be able to create an instance with specific data then add a constructor to do that, e.g.

    Public Structure Shape
    
        Public ReadOnly Property X As Integer
        Public ReadOnly Property Y As Integer
    
        Public Sub New(x As Integer, y As Integer)
            Me.X = x
            Me.Y = y
        End Sub
    
    End Structure
    

    You then create an instance of that type as you would any other:

    Dim shape1 As New Shape(15, 20)