Enumerations, Structures and Tuples
13.1 Enumerations
[Enum] uses square brackets because Enum is a keyword (escaped identifier).
Public Enum OrderStatus
Pending ' 0
Shipped ' 1
Delivered ' 2
Cancelled = 99
End Enum
Public Enum Priority As Byte ' underlying type
Low = 1
Medium = 2
High = 3
End Enum
<Flags>
Public Enum Permissions
None = 0
Read = 1
Write = 2
Execute = 4
All = Read Or Write Or Execute
End Enum
Dim status = OrderStatus.Shipped
Console.WriteLine(status.ToString() & " " & CInt(status))
Dim parsed = [Enum].Parse(Of OrderStatus)("Delivered")
Dim ok = [Enum].TryParse("Cancelled", parsed)
For Each s As OrderStatus In [Enum].GetValues(GetType(OrderStatus))
Console.WriteLine(s)
Next
Dim perms = Permissions.Read Or Permissions.Write
Console.WriteLine(perms.HasFlag(Permissions.Write)) ' True
perms = perms And Not Permissions.Write ' remove a flag13.2 Structures (Value Types)
Value type (stack/inline) Reference type (heap) Copies the reference No (can implement interfaces) Always (parameterless) Resets to default values Small, immutable data (< 16 bytes)
Public Structure Point
Public X As Double
Public Y As Double
Public Sub New(x As Double, y As Double)
Me.X = x
Me.Y = y
End Sub
Public Function DistanceTo(other As Point) As Double
Return Math.Sqrt((X - other.X) ^ 2 + (Y - other.Y) ^ 2)
End Function
Public Overrides Function ToString() As String
Return $"({X}, {Y})"
End Function
End Structure
Dim p1 As New Point(0, 0)
Dim p2 = New Point(3, 4)
Dim p3 = p2 ' COPY (value semantics)
p3.X = 100 ' p2 unchanged
Console.WriteLine(p1.DistanceTo(p2))13.3 Tuples (VB 15+)
Dim person = (Name:="Ana", Age:=30) ' named tuple (ValueTuple)
Console.WriteLine(person.Name & " " & person.Age)
Dim pair As (String, Integer) = ("Bo", 25)
Console.WriteLine(pair.Item1)
Dim inferred = (name, age) ' element names inferred from variables (VB 15.3)
Function Divide(a As Integer, b As Integer) As (Quotient As Integer, Remainder As Integer)
Return (a \ b, a Mod b)
End Function
' Legacy System.Tuple: Tuple.Create("x", 1).Item1