Structures and Enums
Prerequisites: Classes and objects
Enums
An enumeration gives names to a fixed set of related values:
Public Enum OrderStatus
Pending
Paid
Shipped
Cancelled
End Enum
Module Program
Function Describe(status As OrderStatus) As String
Select Case status
Case OrderStatus.Pending : Return "waiting for payment"
Case OrderStatus.Paid : Return "ready to ship"
Case OrderStatus.Shipped : Return "on its way"
Case Else : Return "no longer active"
End Select
End Function
Sub Main()
Dim s = OrderStatus.Paid
Console.WriteLine(s)
Console.WriteLine(CInt(s))
Console.WriteLine(Describe(s))
Console.WriteLine([Enum].Parse(Of OrderStatus)("Shipped") = OrderStatus.Shipped)
For Each value In [Enum].GetValues(Of OrderStatus)()
Console.Write(value.ToString() & " ")
Next
Console.WriteLine()
End Sub
End Module
1
1
ready to ship
True
Pending Paid Shipped Cancelled
- Enum values are integers underneath, starting at 0.
- The colon
:puts two statements on one line — handy for shortCasebranches. [Enum]is in brackets becauseEnumis also a VB keyword.
Flags
Mark an enum <Flags> and give its values powers of two to combine
them:
<Flags>
Public Enum Permissions
None = 0
Read = 1
Write = 2
Delete = 4
End Enum
Module Program
Sub Main()
Dim p = Permissions.Read Or Permissions.Write
Console.WriteLine(p)
Console.WriteLine(p.HasFlag(Permissions.Write))
Console.WriteLine(p.HasFlag(Permissions.Delete))
End Sub
End Module
3
True
False
<Flags> is an attribute — extra information attached to code, in
angle brackets.
Structures
A Structure is like a class, but it's a value type: assigning it
copies the whole value.
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 Overrides Function ToString() As String
Return $"({X}, {Y})"
End Function
End Structure
Module Program
Sub Main()
Dim a As New Point(1, 2)
Dim b = a ' a copy
b.X = 99
Console.WriteLine($"{a} {b}")
Console.WriteLine(a.Equals(New Point(1, 2)))
End Sub
End Module
(1, 2) (99, 2)
True
Changing b didn't change a — compare that with the class example in
Classes and Objects. Structures also compare by value with Equals.
Structure or class?
Use a Structure for small, simple values that behave like numbers —
points, colors, money amounts — ideally immutable. Use a Class for
everything else: objects with identity, behavior, or a lot of data.
.NET's own Integer, Date, and Decimal are structures.