// this is strange, the msg shouldn't be accessible here.
private
members are accessible inside the class, they are not accessible outside the class.
Private - MSDN
The private keyword is a member access modifier. Private access is the
least permissive access level. Private members are accessible only
within the body of the class or the struct in which they are
declared
For your other question:
So, obj2's private member is accessed from another object obj1. I
think this is kind of strange.
You are passing address of obj2
to an instance method of obj1
, and then accessing obj2
's private member msg
in the method and changing its value. But since both of them are of same type, you get the impression that you are accessing other class private member.
Try it with two different classes and you will be able to understand it better.
Consider if you have another class defined as:
class B
{
public void SomeMethod(C obj, string arg)
{
obj.msg = arg; // that is an error.
}
}
now you can't access private member msg
since you are trying to access it outside of the class, in your example, you are accessing the class member inside the class.
There could be an argument that why C# allows instance.PrivateMember
inside the class, the language designers could have restricted the usage of private to this.PrivateMember
, so that the private member is only accessible with the current instance. If that would have been the case then your code would raise the error on obj.msg = arg;
. Apparently the C# designers chosen the private to instance access instead of private to current instance only, so the basic rule is that private
members are accessible inside the class, whether with the this
(current instance) or with an instance of same type. For more discussion why this was done, you can see this question