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.

How do I do that?

VB recognizes three levels of accessibility. Arranged from most to least permissive, these are:

  • Public (available to all classes in all assemblies)

  • Friend (available to all code in all the classes in the current assembly)

  • Private (only available to code in the same class)

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 ...

Get Visual Basic 2005: A Developer's Notebook 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.