Private Members Are Not Instance Based
I always thought that private member fields in a class were instance based.
I was looking for some interesting reading the other night while sitting around at work waiting for something to go wrong with an upgrade that was being rolled out (at which point I got to come in with my hydrospanner and fix it). I started surfing around and found this small little document: The Visual Basic Language Specification 8.0 (Beta 2), from a link on Paul Vick's site.
Well I found it an interesting read, OK? Want to make something of it? :)
I'm nowhere near done with this sucker yet - about page 80 of over 300. I figured I might come across some new feature that I hadn't discovered yet, and there's no place like the horses mouth.
In the 80 pages I've got through, I've discovered so far only one thing that I didn't know. I've also uncovered a couple of code sample errors, a mis-wording, and a suggestion for a change in some wording that's always bugged me. I've tried to contact Paul to see if he's willing to accept comments and edits and bugs, but I'm still waiting to hear back from him.
Anyway, the new thing I learned. In VB8 and (having tested it) in VB7 and C# private member variables are accessible on any instance within class code, not only in the 'Me' context. A lot of people may know this, but it's just something that never came up for me - I never thought it possible, and so never tried.
An example might make it a little clearer.
Public Class TestClass
Private msSomeString As String
Public Property SomeString() As String
Get
Return msSomeString
End Get
Set(ByVal Value As String)
msSomeString = Value
End Set
End Property
End Class
Here's a simple class. If you have some code that uses it you can't access msSomeString without using reflection.
Dim oTest As New TestClass
oTest.msSomeString = "This is some string"
This doesn't work - you get a nice blue squiggly line underneath the call to msSomeString.
But what if you're within some instance of TestClass?
Public Class TestClass
Private msSomeString As String
Public Property SomeString() As String
Get
Return msSomeString
End Get
Set(ByVal Value As String)
msSomeString = Value
End Set
End Property
Public Function GiveMeThePrivateMember(ByVal poTestClass As TestClass) As String
Return poTestClass.msSomeString
End Function
End Class
Now if we call it like this:
Dim oTest As New TestClass
Dim oTest2 As New TestClass
oTest.SomeString = "This is some string"
oTest2.SomeString = "This is some other string"
Debug.WriteLine(oTest.GiveMeThePrivateMember(oTest2))
What we get printed out is oTest2's msSomeString, not oTest's.
I'm not sure if I can or want to make use of this - if it took me this long to find out, perhaps it's not a very obvious feature, and therefore a bit confusing for other developers to have to maintain later.
But it's certainly interesting. I like learning new things :)