Cannot modify the return value... because it is not a variable

H

Hvid Hat

class Sprite
{
private Vector2 position;
public Vector2 Position
{
get { return position; }
set { position = value; }
}
...
}

class Vehicle : Sprite
{
public void Update()
{
Position.X += velocity.X; // <--- Cannot modify the return value
}
}

How to fix? And yes, I'm not an experienced C#-programmer :)
 
M

Marc Gravell

Vector2 is a struct, yes?

The problem is that when you get a struct, you actually get a *clone*
(a blit). If the compiler let you do this, you would edit the clone
and then discard the clone - i.e. nothing useful. I also recommend not
making structs "mutable" - this leads to too many problems to count.
But anyway, I would do something like:

Vector2 old = Position;
Position = new Vector2(old.X + velocityX, ...);

or perhaps, if velocity is also a vector (and is your code), implement
the + operator for Vector2, and use:

Position += velocity;

which is much cleaner. If it isn't your code, you could write a
separate Add method, perhaps as an "extension" method:

Position = Position.Add(velocity);

Marc
 
A

Alun Harford

Hvid said:
class Sprite
{
private Vector2 position;
public Vector2 Position
{
get { return position; }
set { position = value; }
}
...
}

class Vehicle : Sprite
{
public void Update()
{
Position.X += velocity.X; // <--- Cannot modify the return value
}
}

How to fix? And yes, I'm not an experienced C#-programmer :)

This code isn't trying to do what you think it's trying to do...

Vector2 is a struct, so your call in Update first *copies* Position onto
the stack, adds velocity.X to the new Vector2's 'X' and then throws it
away. The original value was never modified.

The C# compiler catches your mistake in this case (phew!). You instead
need to do:

Position = new Vector2(Position.X+velocity.X, Position.Y);

The difference between value and reference types is fundamental in C# -
the C# specification describes that difference immediately after "hello,
world"

See section 8.2 of the C# specification for more information:

http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf

Alun Harford
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top