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 the property is implemented as a pair of property procedures, the program can treat the value as a simple property. For example, suppose that the OrderItem class contains the preceding code. Then the following code sets the Value property for the OrderItem object named paper_item:

paper_item.Value = 19.95F

You can add property procedures to any type of object module. For example, you can use property procedures to implement a property for a form or for a class of your own.

It’s less obvious that you can also use property procedures in a code module. The property procedures look like an ordinary variable to the routines that use them. If you place the previous example in a code module, the program could act as if there were a variable named Value defined in the module.


EASIER EXTENSIONS
The Extension attribute is defined in the System.Runtime.CompilerServices namespace. Using an Imports statement to import that namespace makes it easier to write extensions.

For more information on property procedures, see the section “Property Procedures” in Chapter 14.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.144.214