. Advertisement .
..3..
. Advertisement .
..4..
I am new to csharp and searching the “cannot modify the return value of because it is not a variable” to understand it better. It seems it doesn’t work as expected when I used some suggestions before. Here is the command line I use:
public Point Origin { get; set; }
Origin.X = 10; // fails with CS1612
The error I’m getting is below:
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.
Please give me the solution to this issue.
The cause:
This error happens because of
Point
, it is a value type (struct
). It means that when you try to access theOrigin
property, you are accessing to a copy value of the class’s value but not the actual value (class
). If you set theX
Property on it, you will set the property on the copied property and then remove it and keep the original value. The compiler will warn you, perhaps this is not what you intended.Solution:
You can easily solve this error by changing the
X
value as these following steps:Using a backing variable won’t help.
The
Point
type can be described as a Value type.The entire Point value must be assigned to the Origin property.
Problem is, when you access the Origin property, what you get back by the
get
? A copy of the Point structure in your Origin properties auto-created fields. This means that if you modify the X field, the copy will not affect the underlying one. This is detected by the compiler and you get an error.Even if your backing variable was your own, your
get
would look something like this:You would still need to return a copy the Point structure, and you’d receive the same error.
Hmm… after reading your question carefully, perhaps you mean to modify the back variable directly within your class?
Yes, that is what you would require.