Recently I’ve found an interesting behavior of private keyword and how it actually works.

Let’s look at a simple class:

internal class Test
{
    public int Value { get; set; }
 
    public void PublicMethod(Test test)
    {
        test.privateMethod();
    }
 
    private void privateMethod()
    {
        Value++;
    }
}

Regardless of calling a private method (highlighted line) of another instance of Test inside PublicMethod() the code compiles and works correctly! You might think that private access modifier completely forbids accessing instance members from outside.

But if you look attentively into the “C# Language Specification” you will find lines:

The intuitive meaning of private is “access limited to the containing type”.

Don’t know why such behavior is intuitive, but personally, I expected that private members are completely encapsulated inside a class instance.

Specification explains that private forbids accessing only from another types. Inside some specific class you can easily access private members of instances of the same class.

The same rule works for other access modifiers – they all are applied on type, not instance.

A tricky question for interview 🙂

Add comment