If I have:
class Test
{
private Vector2 v;
public Vector2 Velocity
{
get { return v; }
set { v = value; }
}
}
and then:
Test t = new Test();
t.Velocity = new Vector2(2, 2);
t.Velocity.Normalize();
Console.WriteLine(t.Velocity); // here not normalized
Vector2 tmp = t.Velocity;
tmp.Normalize();
t.Velocity = tmp;
Console.WriteLine(t.Velocity); // here normalized
Console.Read();
Why if I directly try to call Normalize on the property Velocity it is not normalized
and with a tmp Vector2 it is?
P.S.
Vector2 is a struct:
public struct Vector2 : IEquatable<Vector2>
{
public float X;
public float Y;
...
public void Normalize() {...}
}
List item
I guess that in your case
Vector2is a value type (struct).In that case, in your first example, you will get a copy of
vreturned by the get part of theVelocityproperty and you will callNormalizeon the copy, effectively doing nothing, since the copy goes out of scope after the call to Normalize.If Vector2 had been a reference type (class), this would have worked as you expected without having to create a new object first, and then assign it using the set part of
Velocity.Remember that mutable structs are evil. If you always make your structs immutable, you should not get into problems like this.