Note that there are some explanatory texts on larger screens.

plurals
  1. PODoesn't this defeat the whole purpose of having read-only properties?
    primarykey
    data
    text
    <p>I know how to use properties and I understand that they implicitly call underlying <code>get</code> and <code>set</code> accessors, depending on whether we are writing to or reading from a property. </p> <pre><code>static void Main(string[] args) { A a = new A(); (a.b).i = 100; } class A { private B _b = new B(); public B b { get { return _b; } } } class B { public int i; } </code></pre> <p>What code <code>(a.b).i = 100;</code> essentially does is that first property’s <code>get</code> accessor returns a reference to an object <code>_b</code>, and once we have this reference, we are able to access <code>_b’s</code> members and change their values. </p> <p>Thus, in our example, having read only property only prevents outside code from changing the value of a reference variable <code>_b</code>, but it doesn’t prevent outside code from accessing <code>_b’s</code> members. </p> <p>So it seems that property can only detect whether we are trying to read from or write to a variable ( in our case variable <code>_b</code> ) located on the stack, while it’s not able to detect whether we’re trying to also write to members of an object to which the variable on the stack ( assuming this variable is of reference type ) points to.</p> <p>a) But doesn’t that defeat the whole purpose of having read-only properties? Wouldn’t it be more effective if properties had the ability to also detect whether we’re trying to access members of an object returned by get accessor( assuming backing field is of a reference type )?</p> <p>thank you</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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