Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 93,282 times

Contents

Related Categories

Introduction to Class Programming - Read-Only Property

tengtium

Read-Only Property

If you look at Visual Basic how it handle its own object, such as form and controls, some properties can be both read and be written to.  For example, you cannot modify the Height property of a ComboBox even at design time and you cannot modify the MultiSelect property of the ListBox at run time. You can also use this technique to limit the access to your class properties, thus making them read-only.

You can make a property to be read-only property by simply omitting its Property Let procedure.  For example, we might add a FullName property to our Student class.

Public Property Get FullName() As String
  ' Raise an error if an FirstName or LastName is empty
   If (Len(m_FirstName) = 0) Or (Len(m_LastName) = 0) Then Err.Raise 5
  ' Else return the Student Fullname
   FullName = m_FirstName & " " & m_LastName
End Property

Now test your read-only property.  Try to issue a command like as shown below:

'this raise an error Compile Error:  Cannot assign to read-only property
objStudent.FullName = "Samantha Aniversario"

Visual Basic raises a Compile Error "Cannot assign to read-only property", because you are trying to assign a value to a read only property.  Your program won't even compile or run until you delete this line of error.  In addition, if we omit either the FirstName and LastName assignment statement (to be precise, omit the call of either FirstName or LastNamePropert Get), Student class will raise an error when we try to execute the read-only property FullName.  The trick is every time we use FullName property, the code will check the value stored in our Private member  m_FirstName and m_LastName.  If either of the two property does not contain any value, there is no reason to return the value of FullName. In fact, have you ever met a person with only have a FirstName or LastName?

Comments