Private Class Variables

Cory Smith has a set of posts on some of the differences between VB6 and VB10.There’s one which I think needs a bit further clarification: Private Class Variables.

In VB7 and later, you can access private class variables from another instance of the class. So let’s say you had a class A with a private field _z, and instances a1 and a2.In this case a2 can read and modify a1._z. 

An example of this might be if you have a class that has a private field to track changes; you might expose whether or not the class has changes as a ReadOnly property, but you’d want the backing field as Private so as it can’t be modified from outside the class, e.g:

Class Customer
   Private _hasChanges As Boolean
   Private _FirstName As String

Public ReadOnly Property HasChanges As Boolean
End Get
   End Property

Public Property FirstName As String
End Get
      Set(value As String
If value <> _FirstName Then
            'TODO: Raise PropertyChanging notification
            _hasChanges = True
            _FirstName = value
'TODO: Raise PropertyChanged notification
         End If
      End Set
   End Property

Public Shared Function Clone(source As Customer) As Customer
      Dim cust As New Customer
      cust._FirstName = source._FirstName
      cust._hasChanges = source._hasChanges
End Function


Note the Clone function, where the code has access to the private variable of a second instance. This makes the language a lot more powerful and flexible. Benefits include:

  • access to fields in Shared methods
  • provide deep clone and equality methods
  • Assists with Factory methods

there’s no real downside to this, as only code written in the same class as the field  is defined in can modify the field. Code in derived classes would need the field to be declared as Protected, not Private, so Private remains Private to the code you write.

In terms of VB6 to VB7+, this is a non breaking change.  It was an addition to the language that makes a lot of sense as the language moved to be more object orientated.  So to claim that this is somehow significant impeding change is really just nonsense: zero impact on existing code, and provides greater flexibility when writing new code.