PROPERTY PROCEDURES

Property procedures are routines that can represent a property value for a class. The simplest kind of property is an auto-implemented property. Simply add the Property keyword to a variable declaration as shown in the following code:

Public Property LastName As String

If you want, you can give the property a default value as in the following code:

Public Property LastName As String = "<missing>"

Behind the scenes, Visual Basic makes a hidden variable to hold the property’s value. When other parts of the program get or set the value, Visual Basic uses the hidden variable.

This type of property is easy to make but it has few advantages over a simple variable. You can make the property more powerful if you write your own procedures to get and set the property’s value. If you write your own procedures you can add validation code, perform complex calculations, save and restore values in a database, set breakpoints, and add other extras to the property.

A normal read-write property procedure contains a function for returning the property’s value and a subroutine for assigning it.

The following code shows property procedures that implement a Value property. The Property Get procedure is a function that returns the value in the private variable m_Value. The Property Set subroutine saves a new value in the m_Value variable.

Private m_Value As Single
 
Property Value() As Single
    Get
        Return m_Value
    End Get
 
    Set(Value As Single)
        m_Value = Value
    End Set
End Property

Although ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.