anathema's picture

Vector3d operators

I notice that the implementation of (eg) Vector3d operator + is:

        public static Vector3d operator +(Vector3d left, Vector3d right)
            left.X += right.X;
            left.Y += right.Y;
            left.Z += right.Z;
            return left;

I am curious as to why it was done this way - I would have expected it to read:

        public static Vector3d operator +(Vector3d left, Vector3d right)
            return new Vector3d(left.X + right.X, left.Y + right.Y, left.Z + right.Z);

If you write:

    Vector3d first = new Vector3d(1, 1, 1);
    Vector3d second = new Vector3d(2, 2, 2);
    Vector3d result = first + second;

then I'd expect result to have the value (3, 3, 3) and first and second to remain unchanged. The current implementation is really a += rather than a +.


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kvark's picture

'left' is passed by value (it's a structure, System.ValueType).
So we are changing our local copy, not the original passed vector.

I'm using vector operations extensively. I'm sure 99% of them are correct.

anathema's picture

So it is - sorry, didn't notice that! :-(