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

c#, private-members

Solution

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!

Problem

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?

Original source