Acidic
Acidic

Reputation: 6282

Why can't the compiler figure this out? (Properties)

When working with mutable structs and properties, it seems strange to me that the compiler can figure some things out, but can't do the same for other rather obvious things.

Take for example the following automatic property:

Vector2 Vector { get; set; }

Instead of typing this:

Vector2 v = Vector;
v += new Vector2(5, 7);
Vector = v;

The compiler is smart enough to let me do this: (Mutability of struct has no effect here)

Vector += new Vector2(5, 7);

But it seems that the compiler isn't smart enough to let me do the following even though I have access to both the setter and the getter -

Vector.X += 4;

Instead I am forced to do this 'manually' -

Vector2 v = Vector;
v.X += 4;
Vector = v;

Is there any particular reason why the compiler team decided to allow the first shorthand form but not the second one?
Aside from the suggested way being obviously more concise, I also imagine that it could potentially allow more efficient inlining for the NGEN/JIT, since it is clear that the copy produced by the getter isn't used anywhere else. (only if this could in some way be reflected in the IL code)

Upvotes: 2

Views: 120

Answers (2)

Samuel Neff
Samuel Neff

Reputation: 74899

It's not a matter of the compiler being smart enough, it's a matter of what the code compiles to.

Vector += new Vector2(5, 7);

compiles to

Vector = Vector + new vector2(5,7);

so we have an assignment. All fine.

Vector.X += 2;

Compiles to

var v = Vector;
v.X = v.X + 2

No assignment back to Vector.

Upvotes: 2

GSerg
GSerg

Reputation: 78135

If Vector2 is a struct (a value type), then assigning to someObject.Vector.X would assign to a temporary copy returned by the Vector property. This never makes sense and is therefore disallowed.

See Why are mutable structs “evil”? for general reference and some links.

Upvotes: 2

Related Questions