Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private field accessible from another instance of the same class [duplicate]

I do not get the following..I always thought I can access private fields only from class which the field was declared in. However in this case I am able to access it:

class Session
{
    List<client> ListOfClients = new List<client>();

    public void IterateClients(Action<client> action)
    {

    }
}

class client
{
    private int A;

    Session area;

    public void SendData()
    {
        area.IterateClients(delegate(client c)
        {
            c.A = 5; //how come this is accessible?
        });
    }
}
like image 770
Petr Had Avatar asked Dec 12 '22 07:12

Petr Had


1 Answers

You can only access private data from the CLASS it is a member of. Two objects of the same class can access each other's private parts.

Legal:

class c1
{
        private int A;

        public void test(c1 c)
        {
        c.A = 5;

        }

}

Illegal:

class c2
{
  public void test(c1 c)
  {
     c.A = 5;
  }
}
like image 191
Sam Sussman Avatar answered Dec 14 '22 20:12

Sam Sussman