471,330 Members | 1,639 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

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

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 :-)
Jun 27 '08 #1
2 13199
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
Jun 27 '08 #2
Hvid Hat wrote:
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/pu...T/Ecma-334.pdf

Alun Harford
Jun 27 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Doug Jordan | last post: by
4 posts views Thread by Markus Dehmann | last post: by
18 posts views Thread by Pedro Pinto | last post: by
6 posts views Thread by Håkan Johansson | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.