2.12. Safeguard Properties with Split Accessibility
Most properties consist of a property get procedure (which allows you to retrieve the property value) and a property set procedure (which allows you to set a new value for the property). In previous versions of Visual Basic, the declared access level of both procedures needed to be the same. In VB 2005, you can protect a property by assigning to the set procedure a lower access level than you give to the get procedure.
Note: In the past, there was no way to create a property that everyone could read but only your application could update. VB 2005 finally loosens the rules and gives you more flexibility.
2.12.1. How do I do that?
VB recognizes three levels of accessibility. Arranged from most to least permissive, these are:
Imagine you are creating a DLL component that's going to be used by another application. You might decide to create a property called Status that the client application needs to read, and so you declare the property Public:
Public Class ComponetClass Private _Status As Integer Public Property Status( ) As Integer Get Return _Status End Get Set(ByVal value As Integer) _Status = value End Set End Property End Class
The problem here is that the access level assigned to the Status property allows the client to change it, which doesn't make sense. You could make Status a read-only property (in other words, omit the property set procedure altogether), but that wouldn't allow other classes that are part of your applications and located in your component assembly to change it.
The solution is to give the property set procedure the Friend accessibility level. Here's what the code should look like, with the only change highlighted:
Public Property Status( ) As Integer Get Return _Status End Get Friend Set(ByVal value As Integer) _Status = value End Set End Property
2.12.2. What about...
...read-only and write-only properties? Split accessibility doesn't help you if you need to make a read-only property (such as a calculated value) or a write-only value (such as a password that shouldn't remain accessible). To create a read-only property, add the ReadOnly keyword to the property declaration (right after the accessibility keyword), and remove the property set procedure. To create a write-only property, remove the property get procedure and add the WriteOnly keyword. These keywords are nothing newthey've been available since Visual Basic .NET 1.0.