Properties
Prerequisites: Classes and objects
Public fields let anyone set any value. Properties look like fields from the outside but run code when read or written, so a class can validate and compute values.
Auto-implemented properties
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Country As String = "Unknown"
End Class
Module Program
Sub Main()
Dim p As New Person() With {.Name = "Ada", .Age = 36}
p.Age += 1
Console.WriteLine($"{p.Name}, {p.Age}, {p.Country}")
End Sub
End Module
Ada, 37, Unknown
Public Property Name As String creates a hidden field plus a getter
and setter. This is the normal way to expose data from a class.
Properties with logic
Public Class Thermostat
Private _target As Double = 20
Public Property Target As Double
Get
Return _target
End Get
Set(value As Double)
_target = Math.Max(5, Math.Min(30, value))
End Set
End Property
Public ReadOnly Property IsHeating As Boolean
Get
Return _target > 21
End Get
End Property
End Class
Module Program
Sub Main()
Dim t As New Thermostat()
t.Target = 42
Console.WriteLine($"{t.Target} {t.IsHeating}")
t.Target = 18
Console.WriteLine($"{t.Target} {t.IsHeating}")
End Sub
End Module
30 True
18 False
Setreceives the new value (conventionally namedvalue) and can validate or clamp it.- A
ReadOnly Propertyhas only aGet— a computed value callers can't assign. - An underscore prefix (
_target) is a common convention for the field behind a property.
Read-only auto-properties
Public Class Order
Public ReadOnly Property Id As Integer
Public ReadOnly Property Created As Date = New Date(2025, 3, 9)
Public Sub New(id As Integer)
Me.Id = id
End Sub
End Class
Module Program
Sub Main()
Dim o As New Order(7)
Console.WriteLine($"Order {o.Id} created {o.Created:yyyy-MM-dd}")
End Sub
End Module
Order 7 created 2025-03-09
A ReadOnly auto-property can only be set in its declaration or in a
constructor (Sub New, next lesson) — perfect for values that should
never change after the object is created.
Common mistakes
- Making everything
Publicfields. Use properties — they let you add validation later without breaking callers, and data binding in Windows Forms and WPF works with properties only. - Doing slow work (database calls) in a property getter. Callers expect properties to be cheap; use a method for expensive operations.