Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can private member variable be changed by class instance?
    text
    copied!<pre><code>class TestClass { private string _privateString = "hello"; void ChangeData() { TestClass otherTestClass = new TestClass(); otherTestClass._privateString = "world"; } } </code></pre> <p>This code compiles in C# and the equivalent works in PHP, but can someone explain the reason why <code>otherTestClass._privateString</code> can be changed here ? </p> <p>I would have thought an instance of a class should not be able to change a private member variable under any circumstances, and that trying to access <code>otherTestClass._privateString</code> would give an 'inaccessible due to protection level' error. </p> <p>This is not the case though, so why does instantiating an object inside its own class let you access the private members ? And should it, doesn't this break encapsulation to an extent ? Or am I missing something obvious ?</p> <ul> <li>(I'm not asking if the above class design is good practice, just wondering about the theory behind it.)</li> </ul> <p><b>Edit</b> - Thanks for the answers and comments. To clarify, I'm also interested in knowing if being able to do this is regarded as a positive feature, or if it's a necessary tradeoff for better compile-time checking/code clarity/because most other languages do it that way or whatever. It seems to me ideally the compiler would prevent or warn you about this, but then I'm far from a language designer. Any examples of how it being this way lets you do something useful (without violating encapsulation) that would otherwise be difficult or impossible would be great.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload