Search code examples
c#propertiesxnaaccessor

XNA's Vector2 class, property returns an error when attempting to change its value


I will first illustrate my issue with some code:

class ExampleClass
{
    private Vector2 _myVector;

    public Vector2 MyVectorProperty { get { return _myVector; } set { _myVector = value; } }

    private void MyMethod()
    {
        _myVector = Vector2.Zero; // Setting to zero

        MyVectorProperty.X = 5; //Cannot modify the expression because it is not a variable (returns an error)

        _myVector.X = 5; //Works fine!
    }
}

As you can see, I am getting the error "Cannot modify the expression because it is not a variable" when trying to change the value of X and Y on the vector using the property. I am unsure why this happens and haven't had any luck looking on the net and i was wondering why this is and how (if) I can fix it?

Another sub question, is it good programming practice to use the public properties or the private/protected fields when working inside the class they belong to?


Solution

  • You should be happy compiler does not let you do so, otherwise you'll be really surprised with result of operation being lost.

    • MyVectorProperty is property - which means getting the value is call to a function returning the value (something like this.get_MyVectorProperty()).
    • Since type of the MyVectorProperty is Vector2 which is struct it means that value returned by the get_... function is a copy of value, not reference like it would be in case of normal class.
    • Changing field X of above copy would simply change X inside of copy of the value, and since that copy of the value is not assigned to anything it will be lost.