Structs (Visual Basic)

A structure (or struct) is a value type that can encapsulate related data and functions. Structures are useful for creating lightweight objects that represent simple data values. Unlike classes, which are reference types, structures are stored directly where they are declared, either on the stack or inline within another object.

Defining a Structure

You define a structure using the Structure and End Structure statements. A structure can contain fields, properties, methods, events, and even other structures.

Public 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 Function DistanceFromOrigin() As Double
        Return Math.Sqrt(X * X + Y * Y)
    End Function
End Structure

Value Types vs. Reference Types

The fundamental difference between structures and classes in Visual Basic is their type:

Benefits of Using Structures:

When to Use Structures:

Use structures when you are representing a single value or a small, tightly coupled group of values, such as coordinates (like the Point example), colors, or dates. If your type needs to be inherited from or is expected to grow complex with many methods, a class is usually a better choice.

Working with Structures

You can create instances of structures and access their members just like you would with classes.

' Declare a variable of type Point
Dim p1 As Point
p1.X = 10
p1.Y = 20

' Create a Point using the constructor
Dim p2 As New Point(30, 40)

' Accessing members
Console.WriteLine($"Point 1: ({p1.X}, {p1.Y})")
Console.WriteLine($"Point 2 Distance: {p2.DistanceFromOrigin()}")

' Assignment creates a copy for value types
Dim p3 As Point = p1
p3.X = 100
' p1.X will still be 10, demonstrating that p3 is a copy
Console.WriteLine($"Point 1 X after p3 modification: {p1.X}")
Console.WriteLine($"Point 3 X: {p3.X}")

Default Values

When a structure is declared but not initialized, its members are assigned their default values (0 for numeric types, Nothing for reference types, False for Boolean, etc.).

Structures and Methods

Structures can contain methods, just like classes. These methods operate on the data members of the structure instance.

Struct vs. Class

Feature Structure (Value Type) Class (Reference Type)
Memory Allocation Stack or inline within an object Heap
Assignment Copies the entire value Copies a reference (pointer)
Inheritance Cannot inherit from other structures or classes (except ValueType implicitly) Supports single inheritance from other classes
Garbage Collection Not directly managed by GC (unless part of a heap-allocated object) Managed by GC
Nullability Cannot be Nothing (unless using nullable value types like Nullable(Of Point) or Point?) Can be Nothing
Primary Use Case Small, immutable data representations Complex objects, entities, services