MSDN Documentation

Encapsulation in Visual Basic

Encapsulation is one of the fundamental principles of object‑oriented programming. It allows a class to hide its internal state and require all interaction to be performed through well‑defined interfaces.

Why Use Encapsulation?

Access Modifiers

Visual Basic provides several access modifiers to control visibility:

Example: Encapsulating a Bank Account

Public Class BankAccount
    Private _balance As Decimal

    ' Read‑only property – external code can get the balance but not set it
    Public ReadOnly Property Balance As Decimal
        Get
            Return _balance
        End Get
    End Property

    ' Deposit method – validates the amount before updating the balance
    Public Sub Deposit(amount As Decimal)
        If amount <= 0 Then
            Throw New ArgumentException("Deposit amount must be positive.")
        End If
        _balance += amount
    End Sub

    ' Withdraw method – ensures sufficient funds
    Public Sub Withdraw(amount As Decimal)
        If amount <= 0 Then
            Throw New ArgumentException("Withdrawal amount must be positive.")
        End If
        If amount > _balance Then
            Throw New InvalidOperationException("Insufficient funds.")
        End If
        _balance -= amount
    End Sub
End Class

Best Practices

  1. Keep fields Private and expose them through properties or methods.
  2. Validate input in property setters or public methods.
  3. Prefer ReadOnly properties for data that should not be modified directly.
  4. Document the public API clearly; internal implementation can change.

For a deeper dive, see the related topics: