I have a property enclosing a rectangle I have called it Window.
when I try to use the property to change the location or “X” value of the rectangle, I get an error: “Can not modify the return value of Window because it is not a variable.”
Now I know I can just directly access the variable, but I would prefer to be able just modify the “X” value. I also don’t want to be creating a new rectangle every time I modify it.
So is there something I can add to my property that will let me modify the X value through the property?
This is where I am trying to use the property:
Window.X -= amount;
This is where I have the proprty:
private Rectangle _window;
public Rectangle Window
{
get { return _window;}
set
{
if (/*condition*/)
_window = value;
}
}
Problem is that
Rectangleisstruct. Property accessor is actually a method and when it returns struct it is just copied, so you can’t modify underlying struct that way.Solutions:
r = Window; r.X -= amount; Window = r;By the way you should thank C# compiler for that, becase technically it can modify that X, but it would be field/prop of temporary object, it would make later debugging a hell for you. In C++ it actually compiles.
Also it is good example why structures should be immutable. You just wouldn’t have that temptation.