There are times when we may want a property to be read-only-so that it can’t be changed. In our Person class, for instance, we may have a read-write property for BirthDate, but just a read-only property for Age. In such a case, the BirthDate property is a normal property, as follows:
Public Property BirthDate() As Date
Get
Return mdtBirthDate
End Get
Set(ByVal Value As Date
End Get
Set(ByVal Value As Date)
MdtBirthDate = Value
End Set End Property
The Age value, on the other hand, is a derived value based on BirthDate. This is not a value that should ever be directly altered and, thus, is a perfect candidate for read-only status.
We already have an Age method -implemented as a Function. Remove that code from the Person Class, as we’ll be replacing it with a Property routine instead.
The difference between a Function routine and a Readonly Property is quite subtle. Both return a value to the calling code and, either way, our object is running a subroutine defined by our class module to return the value.
The difference is less a programmatic one than a design choice. We could create all our objects without any Property routines at all, just using methods for all interactions with the object. However, Property routines are obviously attributes of the object, while a Function might be an attribute or a method. By carefully implementing all attributes as Readonly Property routines, and any interrogative methods as Function routines, we will create more readable and understandable code.
To make a property read-only, we use the Readonly keyword and only implement the get block:
Public Readonly Property Age() As Integer
Get Return Cint(DateDiff(Datelnterval.Year, mdtBirthDate, Now()))
End Get End Property
Since the property is read-only, we’ll get a syntax error if we attempt to implement a set block.
