Why Does Private Access Remain Non-Private in .NET Within a Class?

Posted by AMissico on Stack Overflow See other posts from Stack Overflow or by AMissico
Published on 2010-04-10T23:38:40Z Indexed on 2010/04/10 23:43 UTC
Read the original article Hit count: 279

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about .NET

Related posts about class-design