Error: "Cannot modify the return value" c#
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);
Using a backing variable won't help. The Point
type is a Value type.
You need to assign the whole Point value to the Origin property:-
Origin = new Point(10, Origin.Y);
The problem is that when you access the Origin property what is returned by the get
is a copy of the Point structure in the Origin properties auto-created field. Hence your modification of the X field this copy would not affect the underlying field. The compiler detects this and gives you an error since this operation is entirely useless.
Even if you used your own backing variable your get
would look like:-
get { return myOrigin; }
You'd still be returning a copy of the Point structure and you'd get the same error.
Hmm... having read your question more carefully perhaps you actually mean to modify the backing variable directly from within your class:-
myOrigin.X = 10;
Yes that would be what you would need.
By now you already know what the source of the error is. In case a constructor doesn't exist with an overload to take your property (in this case X
), you can use the object initializer (which will do all the magic behind the scenes). Not that you need not make your structs immutable, but just giving additional info:
struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
class MyClass
{
public Point Origin { get; set; }
}
MyClass c = new MyClass();
c.Origin.X = 23; //fails.
//but you could do:
c.Origin = new Point { X = 23, Y = c.Origin.Y }; //though you are invoking default constructor
//instead of
c.Origin = new Point(23, c.Origin.Y); //in case there is no constructor like this.
This is possible because behind the scenes this happens:
Point tmp = new Point();
tmp.X = 23;
tmp.Y = Origin.Y;
c.Origin = tmp;
This looks like a very odd thing to do, not at all recommended. Just listing an alternate way. The better way to do is make struct immutable and provide a proper constructor.