Classes, Objects and Members

9.1 Members of a Class

Store state (Private _x As Integer) Controlled access (Property, auto-properties, ReadOnly, WriteOnly, Default) Behavior (Sub, Function) Sub New(...), Shared Sub New() Notifications (Event) Operator +, Widening Operator CType Classes/enums inside classes

9.2 Example: Encapsulated Domain Class

Public Class Account
    Private _balance As Decimal
    Private Shared _nextNumber As Integer = 1000

    Public ReadOnly Property Number As String
    Public Property Owner As String
    Public ReadOnly Property Balance As Decimal
        Get
            Return _balance
        End Get
    End Property

    Public Event BalanceChanged As EventHandler(Of Decimal)

    Public Sub New(owner As String)
        If String.IsNullOrWhiteSpace(owner) Then Throw New ArgumentException("Owner is required.", NameOf(owner))
        Me.Owner = owner
        _nextNumber += 1
        Number = $"ACC{_nextNumber}"
    End Sub

    Public Sub Deposit(amount As Decimal)
        If amount <= 0 Then Throw New ArgumentOutOfRangeException(NameOf(amount))
        _balance += amount
        RaiseEvent BalanceChanged(Me, _balance)
    End Sub

    Public Function TryWithdraw(amount As Decimal) As Boolean
        If amount <= 0 OrElse amount > _balance Then Return False
        _balance -= amount
        RaiseEvent BalanceChanged(Me, _balance)
        Return True
    End Function

    Public Overrides Function ToString() As String
        Return $"{Number} - {Owner}: {Balance:C}"
    End Function
End Class

9.3 Properties in Depth

Public Property Name As String = "Unnamed"            ' auto-property with an initializer
Public ReadOnly Property CreatedAt As Date = Date.UtcNow
Public Property Email As String
    Get
        Return _email
    End Get
    Private Set(value As String)                       ' asymmetric accessibility
        _email = value?.Trim().ToLowerInvariant()
    End Set
End Property
Private _email As String

Default Public ReadOnly Property Item(index As Integer) As OrderLine   ' indexer: order(0)
    Get
        Return _lines(index)
    End Get
End Property

9.4 Constructors, Initialization Order and Factories

Order: shared field initializers → shared constructor (first use) → instance field initializers → base constructor (MyBase.New) → constructor body.

Chain constructors with Me.New(...). Factory methods (Shared Function Create(...)) enable validation, caching, and descriptive names.

Partial classes split a type across files (designers). Partial methods are optional hooks.

9.5 Modules vs Shared Classes

A Module = a sealed class with all members Shared, imported implicitly into its namespace. Use modules for extension methods and stateless helpers. Prefer classes (with DI) for services.