I am making an Int Vector2 but for some reason even when two of them are equal it sometimes returns false. Any ideas?
public class IntVector2
{
public IntVector2(int _x, int _y)
{
x = _x;
y = _y;
}
public int x, y;
public override int GetHashCode()
{
return x ^ y;
}
public override bool Equals(object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
IntVector2 p = obj as IntVector2;
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(IntVector2 p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public static IntVector2 operator +(IntVector2 a, IntVector2 b)
{
return new IntVector2(a.x + b.x, a.y + b.y);
}
public static IntVector2 operator -(IntVector2 a, IntVector2 b)
{
return new IntVector2(a.x - b.x, a.y - b.y);
}
}
The “==” operator and “.Equals()” methods are not the same thing:
TLDR: Refactor your code as follows:
public class IntVector2
{
public IntVector2(int _x, int _y)
{
x = _x;
y = _y;
}
public int x, y;
public override int GetHashCode()
{
return x ^ y;
}
public override bool Equals(object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
IntVector2 p = obj as IntVector2;
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(IntVector2 p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public static bool operator ==(IntVector2 a, IntVector2 b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y;
}
public static bool operator !=(IntVector2 a, IntVector2 b)
{
return !(a == b);
}
public static IntVector2 operator +(IntVector2 a, IntVector2 b)
{
return new IntVector2(a.x + b.x, a.y + b.y);
}
public static IntVector2 operator -(IntVector2 a, IntVector2 b)
{
return new IntVector2(a.x - b.x, a.y - b.y);
}
}
As a side note (since I’ve made a Integer Vector2 implementation before) I would use a struct instead of a class, if I were you.