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?
why I can access private field?
Because you are inside the same class in which the private field is defined.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With