PROPERTY PROCEDURES
Property procedures are routines that can represent a variable-like value. To other pieces of the program, property procedures look just like variables, so they deserve mention in this chapter.
The following code shows property procedures that implement a Name property. The Property Get procedure simply returns the value in the private variable m_Name. The Property Set procedure saves a new value in the m_Name variable.
Private m_Name As String
Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property
A program could use these procedures exactly as if there were a single public Name variable. For example, if this code is in the Employee class, the following code shows how a program could set and then get the Name value for the Employee object named emp:
emp.Name = "Rod Stephens"
MessageBox.Show(emp.Name)
You might want to use property procedures rather than a public variable for several reasons. First, the routines give you extra control over the getting and setting of the value. For example, you could use code to validate the value before saving it in the variable. The code could verify that a postal code or phone number has the proper format and throw an error if the value is badly formatted.
You can also set breakpoints in property procedures. Suppose that your program is crashing because a piece of code is setting an incorrect value in a variable. If you implement the variable with property procedures, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access