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

Let's look 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 can I access a private field?

Can I use this feature, or maybe it's a bad practice?

+5
source share
7 answers

If in doubt, check the language specification.

According to the C # language specification, section 3.5.1:

3.5.1 Announced Availability

Declared item availability can be one of the following:

  • The publication that is selected by including the public modifier in the participant’s ad. The intuitive meaning of the public is "access is not limited."
  • , . " , ". -Internal, . ", ".
  • ( ), , . ", , ".
  • , . private - " ".

, ( , Cluster) points.

... , : !

+4

?

, .

+9

private . , .

public class A
{
    private int _i;

    public bool AreEqual(A otherObject)
    {
        return this._i == otherObject._i;
    }
}

(- ) . , (). ( getters seters) . , , .


: , , , .

+3

, . , .

.

+2

, . , , ( , , ). .

+2

, , , .

+2
source

Private fields are available inside the type. ComputeDistanceToOtherClusterCLINK is a member of the same sheet. Therefore, the private field must be accessible from the body of the method.

+2
source

All Articles