For the code below
public struct Person
{
public int ID;
public static bool operator ==(Person a, Person b) { return a.Equals(b); }
public stati
My guess is your are getting these warning because compiler doesn't know that you use Equals
in ==
method
Suppose you have this implementation
public struct Person
{
public int ID;
public static bool operator ==(Person a, Person b) { return Math.Abs(a.ID - b.ID) <= 5; }
public static bool operator !=(Person a, Person b) { return Math.Abs(a.ID - b.ID) > 5; }
}
Then
Person p1 = new Person() { ID = 1 };
Person p2 = new Person() { ID = 4 };
bool b1 = p1 == p2;
bool b2 = p1.Equals(p2);
b1 would be true, but b2 false
--EDIT--
Now suppose you want to do this
Dictionary dict = new Dictionary();
dict.Add(p1, p1);
var x1 = dict[p2]; //Since p2 is supposed to be equal to p1 (according to `==`), this should return p1
But this would throw an exception something like KeyNotFound
But if you add
public override bool Equals(object obj)
{
return Math.Abs(ID - ((Person)obj).ID) <= 5;
}
public override int GetHashCode()
{
return 0;
}
you will get what you want.
The compiler just warns you that you can face with similar conditions