Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Object defines operator == or operator != but does not override Object.Equals(object o)

Tags:

c#

I'm programming in C# Unity and have really annoying problem - I want to define special Pair class with following relations:

public class Pair<T1>{
    public int First;
    public T1 Second;

    public bool Equals(Pair<T1> b){
        return First == b.First;
    }

    public static bool operator==(Pair<T1> a, Pair<T1> b){
        return a.First == b.First;
    }   
    public static bool operator!=(Pair<T1> a, Pair<T1> b){
        return a.First != b.First;
    }
}

Which gives me following warning:

Warning CS0660: 'Pair' defines operator == or operator != but does not override Object.Equals(object o) (CS0660) (Assembly-CSharp)

But also when I spawn two objects of Pair type with same First integer, their == operator returns True (as I want). When I only declare Equals function, same == operator returns False value (I understand that somehow Unity compares their addressees in memory), with no warnings. Is there any method to avoid warnings and still get True value of == operator?

like image 622
Cheshire Cat Avatar asked Jul 30 '16 16:07

Cheshire Cat


1 Answers

Just override that method to make the compiler happy :

public override bool Equals(object o)
{
   if(o == null)
       return false;

   var second = o as Pair<T1>;

   return second != null && First == second.First;
}

public override int GetHashCode()
{
    return First;
}

The method you created is a custom equals method, you need to override that of the object class (which is used in the == && != operators)

like image 67
Zein Makki Avatar answered Sep 22 '22 00:09

Zein Makki