1

I am creating a VECTOR object like so, but I am initializing it in the constructor:

public VECTOR position { get; private set; }

I am doing this operation:

position.x += 2;

VECTOR has a variable x defined as:

public double x { get; set; } 

I get the error when I do the +=2 operation that says:

Cannot modify the return value of 'Projectile.position' because it is not a variable

I want to be able to modify the position vector in the current class, and I want it to be accessible but not modifiable in other classes.

Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34
Anon E. Muss
  • 175
  • 10
  • 2
    Please put the class for Vector. – Dr. Stitch Feb 04 '16 at 23:41
  • 3
    I'm guessing Vector is a struct. Make it a class. – Andy Feb 04 '16 at 23:41
  • 1
    `x` isn't a variable, it's a property. Also, you haven't really given enough information. You should consider posting your definition of `VECTOR`. Finally, all caps in a class name goes against standard C# naming conventions. `Vector` would be expected by most C# developers, as would `Position`. – Kenneth K. Feb 04 '16 at 23:47
  • 2
    Please provide a [mcve]. – Enigmativity Feb 04 '16 at 23:50
  • 1
    A quick google on the error message gave me [this question](http://stackoverflow.com/questions/1747654/cannot-modify-the-return-value-error-c-sharp) – Setsu Feb 04 '16 at 23:52

2 Answers2

1

Probably, your problem is with the Vector class actually being a struct. Assume you have the following declarations:

public class Projectile
{
    public VECTOR position { get; private set; }        

    public Projectile()
    {
        position = new VECTOR();
    }
}

public struct VECTOR 
{
    public double x {get; set;} 
}

You cant edit properties of the position property directly because you are accessing a copy of that field (explained here).

If you don`t want to convert your VECTOR into a class you can add a method that updates the position of your projectile:

public void UpdatePosition(double newX)
{       
    var newPosition = position;
    newPosition.x = newX;

    position = newPosition;
}

That will create a copy of the position, then update its x property and override the stored position. And the usage would be similar to this:

p.UpdatePosition(p.position.x + 2);
Community
  • 1
  • 1
JleruOHeP
  • 10,106
  • 3
  • 45
  • 71
-1

Expose the X property (and others) of VECTOR in a class.

public class myObject {
private VECTOR position;
public double X { get{return position.x;}set{position.x=value;}}
}

Usage example: myObject.X += 2;

James
  • 66
  • 2