Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why private field of the class are visible when passing same type as a parameter of method C#?

Let see at this class:

    public class Cluster
    {
        private List<Point> points; //private field

        public float ComputeDistanceToOtherClusterCLINK(Cluster cluster)
        {
            var max = 0f;
            foreach (var point in cluster.points) // here points field are accessible
            {
                  .......
            }
            return max;
        }
    }

why I can access private field?

Can I use this feature or may be it is bad practice?

like image 324
Alexander Avatar asked May 25 '12 13:05

Alexander


2 Answers

why I can access private field?

Because you are inside the same class in which the private field is defined.

like image 132
Darin Dimitrov Avatar answered Oct 22 '22 07:10

Darin Dimitrov


When in doubt, check the language specification.

According to C# language specification, section 3.5.1:

3.5.1 Declared accessibility

The declared accessibility of a member can be one of the following:

  • Public, which is selected by including a public modifier in the member declaration. The intuitive meaning of public is “access not limited”.
  • Protected, which is selected by including a protected modifier in the member declaration. The intuitive meaning of protected is “access limited to the containing class or types derived from the containing class”. -Internal, which is selected by including an internal modifier in the member declaration. The intuitive meaning of internal is “access limited to this program”.
  • Protected internal (meaning protected or internal), which is selected by including both a protected and an internal modifier in the member declaration. The intuitive meaning of protected internal is “access limited to this program or types derived from the containing class”.
  • Private, which is selected by including a private modifier in the member declaration. The intuitive meaning of private is “access limited to the containing type”.

As you can see from the last section, all methods of the containing class (in your case, it's Cluster) have access to the private field points.

...and no, this is not a bad practice at all: this is precisely the purpose of private fields!

like image 44
Sergey Kalinichenko Avatar answered Oct 22 '22 06:10

Sergey Kalinichenko