Search code examples
.netclass-design

In .NET, Why Can I Access Private Members of a Class Instance within the Class?


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? I would like to know the "why" I can do this. Please explain, don't just tell me the rule. 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. The disadvantage is the programmer created a big plate of Spaghetti.

Sincerely,

  • Totally Confused

Class Jack
    Private _int As Integer
End Class
Class Foo
    Public Property Value() As Integer
        Get
            Return _int
        End Get
        Set(ByVal value As Integer)
            _int = value * 2
        End Set
    End Property
    Private _int As Integer
    Private _foo As Foo
    Private _jack As Jack
    Private _fred As Fred
    Public Sub SetPrivate()
        _foo = New Foo
        _foo.Value = 4  'what you would expect to do because _int is private
        _foo._int = 3   'TOTALLY UNEXPECTED
        _jack = New Jack
        '_jack._int = 3 'expected compile error 
        _fred = New Fred
        '_fred._int = 3 'expected compile error 
    End Sub
    Private Class Fred
        Private _int As Integer
    End Class
End Class

Solution

  • This is "normal". Private members are private to the class, not to the particular instance.