I'm using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable?
public Point Origin { get; set; }
Origin.X = 10; // fails with CS1612
Error Message: Cannot modify the return value of 'expression' because it is not a variable
An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.
To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.
This is because Point
is a value type (struct
).
Because of this, when you access the Origin
property you're accessing a copy of the value held by the class, not the value itself as you would with a reference type (class
), so if you set the X
property on it then you're setting the property on the copy and then discarding it, leaving the original value unchanged. This probably isn't what you intended, which is why the compiler is warning you about it.
If you want to change just the X
value, you need to do something like this:
Origin = new Point(10, Origin.Y);