Why Does Private Access Remain Non-Private in .NET Within a Class?
- by AMissico
While cleaning some code today written by someone else, I changed the access modifier from Public to Private on a class variable/member/field. I expected a long list of compiler errors that I use to "refactor/rework/review" the code that used this variable. Imagine my surprise when I didn't get any errors. After reviewing, it turns out that another instance of the Class can access the private members of another instance declared within the Class. Totally unexcepted.
Is this normal? I been coding in .NET since the beginning and never ran into this issue, nor read about it. I may have stumbled onto it before, but only "vaguely noticed" and move on. Can anyone explain this behavoir to me? Am I doing something wrong? I found this behavior in both C# and VB.NET. The code seems to take advantage of the ability to access private variables.
Sincerely,
Totally Confused
Class Foo
Private _int As Integer
Private _foo As Foo
Private _jack As Jack
Private _fred As Fred
Public Sub SetPrivate()
_foo = New Foo
_foo._int = 3 'TOTALLY UNEXPECTED
_jack = New Jack
'_jack._int = 3 'expected compile error because Foo doesn't know Jack
_fred = New Fred
'_fred._int = 3 'expected compile error because Fred hides from Foo
End Sub
Private Class Fred
Private _int As Integer
End Class
End Class
Class Jack
Private _int As Integer
End Class