Creating a read-only property or a write-only property isn’t difficult, as you probably know: just omit the Property Let (or Set, if dealing with objects) or the Property Get procedure, respectively.
There are cases, however, when you want to implement a write-only-read-many property, that is, a property that can be assigned just once and be read any number of times. For example, the ID property of an object should never change after it has been assigned, so you should make it a WORM property. More in general, any property that is then used to retrieve additional information about an object from a database should be a WORM property.
Visual Basic doesn’t offer a built-in mechanism for implementing a write-once read-many property, but it’s easy to do it yourself, using a Static variable, as in the following code snippet:
Private m_ID As LongProperty Get ID() As Long ID = m_IDEnd PropertyProperty Let ID(newValue As Long) Static initialized As Boolean If initialized Then Err.Raise 1001, , "Can't assign this property more than once" End If m_ID = newValue ' remember that the property has been set initialized = TrueEnd Property
If the property has some special or invalid value, you don’t even need to declare an additional Static variable. For example, suppose that the ID property can’t take negative values:
Private m_ID As LongPrivate Sub Class_Initialize() ' initialize ID with an invalid value m_ID = -1End SubProperty Get ID() As Long ID = m_IDEnd PropertyProperty Let ID(newValue As Long) If m_ID <> -1 Then Err.Raise 1001, , "Can't assign this property more than once" ElseIf newValue < 0 Then Err.Raise 1002, , "Invalid value for the ID property" End If m_ID = newValueEnd Property