Why get accessor does not allow the modification of object returned?

Please have a look at the code below:

public class Foo
{
    public System.Windows.Rect s
    {
        get;
        set;
    }
    public Foo()
    {
        s = new System.Windows.Rect(-2, -3, 4, 5); // affects object
        s.Inflate(1.5, 1.5); // no effect at all
    }
}

Is there a way to make the non-const Inflate() method work in this case? If it does not modify my objetc, it means that my Rect object is deeply copied when I access it?

These are my interrogations, but the real question is: why the accessor disallow modification of the object returned if there is a setter too?

Jon Skeet
people
quotationmark

System.Windows.Rect is a structure. Therefore a copy of the struct is returned by the property, rather than a copy of a reference to an object.

Modifying the returned value does nothing, as it's a copy of the value that's actually stored in the backing field for the property. If you try to make the modification directly, the compiler will actually give you an error, because it understands the problem:

// Error: CS1612 Cannot modify the return value of 'Foo.s' because it is not a variable
s.X = 10;

It doesn't do that for method calls as it doesn't know that the method call mutates the struct.

Moral: avoid mutable structs where possible... they cause pain.

people

See more on this question at Stackoverflow