Validation and Protection

Property Let/Get allows you to validate the property in a way that would not be possible with a UDT. In this example, we have a property that can have a discrete set of values. The traffic light can be red, green, or yellow. The constants are defined using an Enum, but this is not sufficient to ensure that the traffic light values fall into this range. You can perform the validation using a Property Let instead.

Public Enum TrafficLight
    RedLight
    GreenLight
    YellowLight
End Enum

Class TLight

Private m_TopLight As TrafficLight
Public Property Let TopLight(newValue As TrafficLight)
    ' You can validate the assignment to TopLight.
    ' Note that Enum will NOT do any checking for you.
    Select Case newValue
        Case RedLight, GreenLight, YellowLight
            m_TopLight = newValue
        Case Else
            ' Raise type mismatch.
            Err.Raise 13
        End Select
End Property
Public Property Get TopLight() As TrafficLight
    TopLight = m_TopLight
End Property

With the following code, only the last line will generate an error:

Dim tl As New TLight
Dim col As TrafficLight
   
 col = RedLight
tl.TopLight = col
    
' Enums do not validate...
col = 1234     ' This works.
' ...but classes do validate.
tl.TopLight = col ' This gets an error.