How Private is Private?
Okay, there's a lot of things that that title might refer to, but this post is about the most boring interpretation :-)
I came across an odd line of code the other day, and after doing some investigating I found out something about private members that I never knew. This is in C#, but I would assume it applies in C++, Java, and any other object oriented language as well.
This is what I discovered: any instance of a class can access the private members of any other instance of that class! In other words, this code is fine:
public class MyClass
{
private int myVar;
public void accessPrivate(MyClass instance2)
{
instance2 = 42;
}
}
Thinking about it, it does make sense (I almost said, on reflection :-) - the access modifier applies on the class level, not the instance level. And it could come in useful, for example when overriding .Equals - but I still find it somewhat disturbing. And I suspect that with intellisense, people may be using this feature without even realising it - you see the private member in the drop-down list, and select it, without stopping to think that you shouldn't even be able to see it (yet another reason that intellisense sometimes makes life too easy).
Doing some googling, I found several discussions about this - in summary, though, someone posts saying "isn't this odd", someone else posts saying "yes, but it's useful", and someone else posts saying "it's data-hiding, not security".
Labels: Coding
0 Comments:
Post a Comment
<< Home