3
public class Class1
{
    private object field;

    public Class1(Class1 class1)
    {
        this.field = class1.field;
    }

    private void Func(Class1 class1)
    {
        this.field = class1.field;
    }
}

This code compiles and works. But why? I always thought that private members are only accessible within the class scope. Also MSDN says so:

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

anth
  • 1,724
  • 1
  • 19
  • 22

4 Answers4

5

That's because by marking it as private, you are telling the compiler that only Class1 may access that variable. Even though your constructor is public, the variable itself is still declared within Class1 and so it has access to modify it.

Even though they could be two different instances, they are the same variable declaration.

However, if I did this from Class2, it would not work:

Class1 c1 = new Class1();
c1.field = "value"; // Won't compile

This is actually explained from your quote:

Private members are accessible only within the body of the class

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Yeah, I noticed that, but can you point some documentation references that explain this behaviour ? – anth Sep 13 '13 at 11:35
4

The private keyword means its private for the class (as stated in MSDN), not the object. So one instance of a class can access the private members of another instance of the class.

cb_dev
  • 379
  • 1
  • 3
  • 16
1

It works because an object can hold anything. If you pass in class1 and the object field is null then the object field will remain null. If that makes sense?

BenM
  • 4,218
  • 2
  • 31
  • 58
1

As long as the code that access that private field is in Class1, you can use it. That's what private means - it's accessible from anywhere inside those {}

Jutanium
  • 421
  • 3
  • 16