Reputation: 29
I am trying to implement cartesian 2D integer coordinate system. I have managed to get +, -, * and / operators working. However, after implementing the == operator in the same way I am getting errors.
My struct is defined as follows:
public struct IntVector2 : IEquatable<IntVector2>
{
// properties
public int x { get; private set; }
public int y { get; private set; }
// constructors
public IntVector2(int x, int y)
{
this.x = x;
this.y = y;
}
// I have removed the XML documentation and operator definitions here
}
NB: I implemented .Equals
and .GetHashCode
according to the .NET guidelines. Hence the IEquateable<IntVector2>
I have also defined the following operators (and many more) within the struct body:
public static bool operator ==(IntVector2 a, Vector2 b)
{
return (a.x == b.x && a.y == b.y);
}
public static bool operator != (IntVector2 a, Vector2 b)
{
return !(a == b);
}
// Once again I removed the XML documentation
And the following overrides:
public override bool Equals(object obj)
{
if (!(obj is IntVector2))
{
return false;
}
IntVector2 intVect2 = (IntVector2)obj;
return (x == intVect2.x && y == intVect2.y);
}
public override int GetHashCode()
{
return (x * 31 + y);
}
In an effort to find a pre-existing answer, I investigated the following links:
https://coding.abel.nu/2014/09/net-and-equals/ --- info and demonstration of equality operator being used
msdn.microsoft.com/en-us/library/c35t2ffz.aspx --- Equality operators
msdn.microsoft.com/en-us/library/7h9bszxx(v=vs.100).aspx --- MSDN guidelines for implementing equality operators
All my other operators work fine, but when I try to compare the equality of 2 IntVector2
s, I get errors. For example:
void Foo(IntVector2 intVectA, IntVector2 intVectB)
{
if (intVectA.Equals(intVectB))
{
IntVector2 C = intVectA + intVectB;
bool isEqual = intVectA == intVectB;
}
}
Gives the error
Operator '==' cannot be applied to operands of type 'IntVector2' and 'IntVector2'
For context I am using this as a learning experience. I can get away without it (using intVectA.x == intVectB.x && intVectA.y == intVectB.y
), but if I just go around the issue I will never learn why this is an error.
Also, my struct compiles completely without any errors.
Upvotes: 1
Views: 398
Reputation: 3542
You're trying to compare an IntVector2
to another IntVector2
, but your implementations of the ==
and !=
operators take an IntVector2
and a Vector2
. I don't see any other mention of a class or struct called Vector2
in your question. Is that a typo? The operators work fine for me if I change them to:
public static bool operator ==(IntVector2 a, IntVector2 b) { ... }
public static bool operator !=(IntVector2 a, IntVector2 b) { ... }
Upvotes: 2