C# members accessibility

Recently I’ve found an interesting behavior of private keyword. Let’s look for a simple class:

internal class Test
    public int Value { get; set; }

    public void PublicMethod(Test test)

    private void privateMethod()

Regardless of calling private method of another instance inside PublicMethod the code compiles and works correctly! You may 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 I expected that private members are completely encapsulated inside class instance.
Specification explains that private forbids accessing only from another types. Inside some 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.