typestar

Structures in Visual Basic

Value types: copied on assignment, methods and all.

Dim origin As New Point
Dim peak As New Point With {.X = 3.0, .Y = 4.0}
Console.WriteLine(origin.DistanceTo(peak))

Dim copy = peak
copy.X = 99.0
Console.WriteLine($"value copy left peak.X at {peak.X}")

Structure Point
    Public X As Double
    Public Y As Double

    Public Function DistanceTo(other As Point) As Double
        Dim dx = X - other.X
        Dim dy = Y - other.Y
        Return Math.Sqrt(dx * dx + dy * dy)
    End Function
End Structure

How it works

  1. Structure members live inline — no heap allocation per point.
  2. With {.X = 3.0} fills fields as the value is made.
  3. Assigning copies the whole value: mutating copy leaves peak alone.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
416
Tokens
104
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 73 seconds.

Type this snippet

Step 1 of 3 in Value types, step 19 of 29 in Language basics.

← Previous Next →