Cannot modify the return value of...

  • Thread starter Thread starter Daisy
  • Start date Start date
D

Daisy

I came across this problem at work, and now at home... I've got an object
that stores its position in a Vector3 object.

Looks like this:

public class Object3D
{
Vector3 _position;
public Vector3 Position
{
get { return _position; }
}
}

But when I try setting a field, like this:

Object3D dan = new Object3D();
dan.Position.X = 10;

I get the error in the subject, because a Vector3 is a value type.

Given I might just want to increase the X position, is there any way I can
change this value, without setting it to a new Vector3 and passing the other
two fields back in?
 
Why would you want to do that? Since Vector3 is a value type, "return
_position" will return the value of object _position. So, you won't be able
to make changes at that point.

You can try making Vector3 a class (so, it becomes Pass-by-reference)

VJ
 
Vijaye Raji said:
Why would you want to do that? Since Vector3 is a value type, "return
_position" will return the value of object _position. So, you won't be able
to make changes at that point.

You can try making Vector3 a class (so, it becomes Pass-by-reference)

Vector3 is a DirectX class, not mine :-)

I did think about wrapping another around it, but it seems a bit silly...
Vector3 is probably a value type for a reason (even though with boxing and
unboxing, I don't see any advantage?!)
 
Hi Daisy,

Since Vector3 is a value type, I believe a *copy* of the "_position" is
actually returned. Since there is no sense in modifying the copy - it won't
be persisted anywhere - the compiler gives you the error in question.

You should introduce a method like Move(xOffset, yOffset, zOffset) or
MoveX(offset) instead, or indeed switch to a reference type to store the
position. The latter approach, however, is more error prone as you have no
control on how and when the object position is modified.
 
You can expose two other properties, say, PositionX and PositionY that would
directly modify the members of Vector3's position member.

Or some method like SetPosition(x, y)...

Sorry, I've run out of ideas and I guess you'd already come up with these
before...

vJ
 
Back
Top