Hazz
Hazz

Reputation: 29

Trying to define a == and != operator for my struct, but I keep getting the "Operator `==' cannot be applied to operands..."

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:

All my other operators work fine, but when I try to compare the equality of 2 IntVector2s, 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

Answers (1)

Joe Farrell
Joe Farrell

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

Related Questions