Structs (Visual Basic)
In Visual Basic, a Structure (or struct) is a value type that can contain data members and methods. Structures are useful for grouping related data without the overhead of a class.
Definition
A structure is declared using the Structure
keyword and ends with End Structure
. By default, structs are sealed and cannot be inherited.
Syntax
Structure StructName
' Fields
Public field1 As DataType
Private field2 As DataType
' Constructors
Public Sub New(param1 As DataType, param2 As DataType)
Me.field1 = param1
Me.field2 = param2
End Sub
' Methods
Public Function ToString() As String
Return $"{field1}, {field2}"
End Function
End Structure
Example
The following example defines a Point
structure that represents a coordinate in a two‑dimensional space.
Structure Point
Public X As Integer
Public Y As Integer
Public Sub New(x As Integer, y As Integer)
Me.X = x
Me.Y = y
End Sub
Public Overrides Function ToString() As String
Return $"({X}, {Y})"
End Function
End Structure
Module Demo
Sub Main()
Dim p1 As New Point(10, 20)
Dim p2 As Point = p1 ' Value copy
p2.X = 30
Console.WriteLine(p1) ' (10, 20)
Console.WriteLine(p2) // (30, 20)
End Sub
End Module
Remarks
- Structs are value types; assigning one struct to another creates a copy.
- They cannot inherit from other structs or classes, but they can implement interfaces.
- Use
ReadOnly
structures for immutable data.
Related Topics
Topic | Description |
---|---|
Classes | Reference types with inheritance support. |
Interfaces | Define contracts for classes and structs. |
Enumerations | Define a set of named constants. |