Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't this defeat the whole purpose of having read-only properties?

Tags:

c#

properties

I know how to use properties and I understand that they implicitly call underlying get and set accessors, depending on whether we are writing to or reading from a property.

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;
}

What code (a.b).i = 100; essentially does is that first property’s get accessor returns a reference to an object _b, and once we have this reference, we are able to access _b’s members and change their values.

Thus, in our example, having read only property only prevents outside code from changing the value of a reference variable _b, but it doesn’t prevent outside code from accessing _b’s members.

So it seems that property can only detect whether we are trying to read from or write to a variable ( in our case variable _b ) 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.

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 )?

thank you

like image 261
flockofcode Avatar asked Jun 16 '10 19:06

flockofcode


2 Answers

Immutability is not transitive; you can't expect mutable objects into an immutable accessor to be immutable.

like image 60
plinth Avatar answered Oct 18 '22 15:10

plinth


Your reference is read only, not your object.

like image 25
Andrew Lewis Avatar answered Oct 18 '22 14:10

Andrew Lewis